package com.ocean.nc.service.impl;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.ConnectException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.github.pagehelper.util.StringUtil;
import com.ocean.common.core.domain.AjaxResult;
import com.ocean.common.core.domain.entity.Config;
import com.ocean.common.core.domain.entity.SysUser;
import com.ocean.common.core.page.ForeResult;
import com.ocean.common.enums.Globals;
import com.ocean.common.utils.*;
import com.ocean.common.utils.file.FileUtils;
import com.ocean.common.utils.uuid.IdUtils;
import com.ocean.elementdict.domain.OElementDict;
import com.ocean.elementdict.service.IOElementDictService;
import com.ocean.metadata.domain.OMetadata;
import com.ocean.metadata.domain.OMetadataElement;
import com.ocean.metadata.service.IOMetadataElementService;
import com.ocean.metadata.service.IOMetadataService;
import com.ocean.nc.domain.ONcUnzip;
import com.ocean.nc.service.IONcUnzipService;
import com.ocean.previewElement.domain.PreviewData;
import com.ocean.previewElement.service.IOPreviewElementService;
import com.ocean.product.domain.OProduct;
import com.ocean.product.domain.OProductReport;
import com.ocean.product.service.IOProductService;
import com.ocean.productCheck.domain.OProductCheckSms;
import com.ocean.productCheck.service.IOProductCheckSmsService;
import com.ocean.productDict.domain.ONCfileMenu;
import com.ocean.productDict.domain.oNcfileMonitor;
import com.ocean.productDict.mapper.oNcfileMonitorMapper;
import com.ocean.productDict.service.ONCfilemeunService;
import com.ocean.productRelease.domain.OProductRelease;
import com.ocean.productRelease.service.IOProductReleaseService;
import com.ocean.resources.domain.OResources;
import com.ocean.resources.service.IOResourcesService;
import com.ocean.system.domain.ODownLog;
import com.ocean.system.domain.ODownOrder;
import com.ocean.system.domain.TSLog;
import com.ocean.system.mapper.TSLogMapper;
import com.ocean.system.service.IODownLogService;
import com.ocean.system.service.IODownOrderService;
import com.ocean.system.service.ISysConfigService;
import com.ocean.workOrder.domain.OWorkOrder;
import com.ocean.workOrder.domain.OWorkOrderItem;
import com.ocean.workOrder.domain.OWorkOrdernccj;
import com.ocean.workOrder.mapper.OWorkOrdernccjMapper;
import com.ocean.workOrder.service.IOWorkOrderService;
import com.sun.mail.smtp.SMTPAddressFailedException;
/*import map.core.LonLatBounds;
import map.core.NetCDFSource;
import map.core.NetCDFSourceExtractor;*/
import map.core.LonLatBounds;
import map.core.NetCDFSource;
import map.core.NetCDFSourceExtractor;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.dom4j.io.SAXReader;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ocean.nc.mapper.ONcFileMapper;
import com.ocean.nc.domain.ONcFile;
import com.ocean.nc.service.IONcFileService;
import com.ocean.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

/**
 * nc文件Service业务层处理
 *
 * @author ocean
 * @date 2023-02-13
 */
@Service
public class ONcFileServiceImpl implements IONcFileService {
    private static Map<String, Long> fileSizeMap = new HashMap<String, Long>();
    protected Logger logger = LoggerFactory.getLogger(getClass());
    private static final int FILE_PAGESIZE = 99999;

    @Autowired
    private ONcFileMapper oNcFileMapper;
    @Autowired
    private IOProductService productService;
    @Autowired
    private IOPreviewElementService previewElementService;
    @Autowired
    private IOMetadataService metadataService;
    @Autowired
    private IOResourcesService resourcesService;
    @Autowired
    private IOProductCheckSmsService productCheckSmsService;
    @Autowired
    private IOProductReleaseService productReleaseService;
    @Autowired
    private IONcUnzipService ncUnzipService;
    @Autowired
    private IOMetadataElementService metadataElementService;
    @Autowired
    private IOElementDictService elementDictService;
    @Autowired
    private IODownLogService downLogService;
    @Autowired
    private oNcfileMonitorMapper oNcfileMonitorMapper;
    @Autowired
    private TSLogMapper tsLogMapper;

    @Autowired
    private ONCfilemeunService onCfilemeunService;
    @Autowired
    private IOWorkOrderService ioWorkOrderService;
    @Autowired
    private IODownOrderService ioDownOrderService;
    @Autowired
    private ISysConfigService configService;

    @Autowired
    private OWorkOrdernccjMapper oWorkOrdernccjMapper;

    /**
     * 获取短信AccessKeyId
     */
    public String getAccessKeyId() {
        return DictUtils.getDictLabel2("params", "accessKeyId", "LTAIqcYijk60jZcz");
    }

    /**
     * 获取短信AccessSecret
     */
    public String getAccessSecret() {
        return DictUtils.getDictLabel2("params", "accessSecret", "pt3jHb1tTwPvK0uh42VQIwjLASu3h6");
    }

    /**
     * 获取短信Regionid
     */
    public String getRegionid() {
        return DictUtils.getDictLabel2("params", "regionid", "cn-hangzhou");
    }

    /**
     * 获取短信SignName
     */
    public String getSignName() {
        return DictUtils.getDictLabel2("params", "signName", "国家海洋预报云服务平台");
    }

    /**
     * 查询nc文件
     *
     * @param id nc文件主键
     * @return nc文件
     */
    @Override
    public ONcFile selectONcFileById(String id) {
        return oNcFileMapper.selectONcFileById(id);
    }

    /**
     * 查询nc文件列表
     *
     * @param oNcFile nc文件
     * @return nc文件
     */
    @Override
    public List<ONcFile> selectONcFileList(ONcFile oNcFile) {
        return oNcFileMapper.selectONcFileList(oNcFile);
    }

    /**
     * 新增nc文件
     *
     * @param oNcFile nc文件
     * @return 结果
     */
    @Override
    public int insertONcFile(ONcFile oNcFile) {
        return oNcFileMapper.insertONcFile(oNcFile);
    }

    /**
     * 修改nc文件
     *
     * @param oNcFile nc文件
     * @return 结果
     */
    @Override
    public int updateONcFile(ONcFile oNcFile) {
        return oNcFileMapper.updateONcFile(oNcFile);
    }

    /**
     * 批量删除nc文件
     *
     * @param ids 需要删除的nc文件主键
     * @return 结果
     */
    @Override
    public int deleteONcFileByIds(String ids) {
        return oNcFileMapper.deleteONcFileByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除nc文件信息
     *
     * @param id nc文件主键
     * @return 结果
     */
    @Override
    public int deleteONcFileById(String id) {
        return oNcFileMapper.deleteONcFileById(id);
    }

    /**
     * 文件归档
     */
    @Override
    //@Transactional
    public void autoFile() {
        smncfile();//归档配置中的文件
        //znwgncfile();//归档智能网格中的文件(智能网格数据归档方法暂不使用)
    }
    /**
     * 扫描ncfile文件夹数据
     */
    public void smncfile(){

        /**
         * 获取文件配置数据
         */
        //#是否归档文件
        String isFile = (String) YamlUtil.loadYaml("sysConfig.yaml").get("is_file");
        //归档服务器路径是 win 还是 linux
        String archive = (String) YamlUtil.loadYaml("sysConfig.yaml").get("archive");
        //文件扫描路径默认为 /cloud/ncfile
        String path = "";

        //非文件归档服务器
        if (!StringUtils.equals("true", isFile)) {
            return;
        }
        //判断是否为win系统
        if(archive.equals("win")){
            String pDir = configService.selectConfigByKey("gdwinpath");
            path = pDir;
        }else{//判断是否为linux系统
            String pDir = configService.selectConfigByKey("gdlinuxpath");
            path = pDir;
        }
        System.out.println(path+"路径");

        /**
         * 获取文件夹下所有文件进行便利归档
         */
        // 创建一个文件对象
        File file = new File(path);
        // 获取该文件夹下的所有文件
        File[] tempList = file.listFiles();
        System.out.println("1.打印文件夹下所有文件：" + tempList.length + "个文件");
        // 判断是否为空
        if (tempList == null) {
            System.out.println("1.文件夹为空,无需归档");
            return;
        }
        //便利所有文件
        for (int i = 0; i < tempList.length; i++) {
            File ncFile = tempList[i];
            //判断配置文件是否为true ，如果是则进行归档
            if (ncFile.isFile()) {
                //获取文件名
                String name = ncFile.getName();
               /* if(name.contains("L0")
                        || name.contains("L1")
                        || name.contains("L2")
                        || name.contains("L3")
                        || name.contains("L4")
                        || name.contains("L5")){
                    System.out.println("2.新加功能FTP接收到的文件入库存储就行，但是这个入库跟云平台原来的入库不一样，不能移走文件，而且入库以后要实时监控各级产品到报情况，相当于把这个业务监控做到云平台里面，另外，就是多加一个功能，就是实现各级产品的加载显示"+ tempList[i]);
                    //智能网格文件归档方法
                    NcautoFile(path, ncFile);
                }else{*/
                    //读取某个文件夹下的所有文件
                    System.out.println("2.普通归档文件：" + tempList[i]);
                    //普通文件归档方法
                    autoFile(path, ncFile);
                //}
            }
            //判断文件是否存在
            if (ncFile.isDirectory()) {
                System.out.println("2."+tempList[i]+"是文件夾");
            }
        }
    }
    /**
     * 扫描znwgncfile文件夹数据，上传智能网格数据
     */
    public void znwgncfile(){
        /**
         * 获取文件配置数据
         */
        //#是否归档文件
        String isFile = (String) YamlUtil.loadYaml("sysConfig.yaml").get("is_file");
        //归档服务器路径是 win 还是 linux
        String archive = (String) YamlUtil.loadYaml("sysConfig.yaml").get("archive");
        //文件扫描路径默认为 /cloud/ncfile
        String path = "";

        //非文件归档服务器
        if (!StringUtils.equals("true", isFile)) {
            return;
        }
        //判断是否为win系统
        if(archive.equals("win")){
            String pDir = configService.selectConfigByKey("gdwinpathznwg");
            path = pDir;
        }else{//判断是否为linux系统
            String pDir = configService.selectConfigByKey("gdlinuxpathznwg");
            path = pDir;
        }
       /* if(archive.equals("win")){
            path = "D:\\znwgncfile";
        }else{//判断是否为linux系统
            path = "/cloud/znwgncfile";
        }*/

        /**
         * 获取文件夹下所有文件进行便利归档
         */
        // 创建一个文件对象
        File file = new File(path);
        long fileSize = getFileSizes(file);
        //判断是否上传完成
        if (fileSizeMap.containsKey(file.getName())) {
            long fileSizeOld = fileSizeMap.get(file.getName());
            if (fileSize != fileSizeOld) {
                logger.info("文件" + file.getName() + "未上传完成");
                fileSizeMap.put(file.getName(), fileSize);
                return;
            } else {
                logger.info("文件" + file.getName() + "上传完成");
                fileSizeMap.remove(file.getName());
            }
        } else {
            fileSizeMap.put(file.getName(), fileSize);
            return;
        }

        // 获取该文件夹下的所有文件
        File[] tempList = file.listFiles();
        System.out.println("1.打印文件夹下所有文件：" + tempList.length + "个文件");
        // 判断是否为空
        if (tempList == null) {
            System.out.println("1.文件夹为空,无需归档");
            return;
        }
        //便利所有文件
        for (int i = 0; i < tempList.length; i++) {
            File ncFile = tempList[i];
            //判断配置文件是否为true ，如果是则进行归档
            if (ncFile.isFile()) {
                //获取文件名
                String name = ncFile.getName();
                if(name.contains("L0")
                        || name.contains("L1")
                        || name.contains("L2")
                        || name.contains("L3")
                        || name.contains("L4")
                        || name.contains("L5")){
                    System.out.println("2.新加功能FTP接收到的文件入库存储就行，但是这个入库跟云平台原来的入库不一样，不能移走文件，而且入库以后要实时监控各级产品到报情况，相当于把这个业务监控做到云平台里面，另外，就是多加一个功能，就是实现各级产品的加载显示"+ tempList[i]);
                    //智能网格文件归档方法
                    NcautoFile(path, ncFile);
                }/*else{
                    //读取某个文件夹下的所有文件
                    System.out.println("2.普通归档文件：" + tempList[i]);
                    //普通文件归档方法
                    autoFile(path, ncFile);
                }*/
            }
            //判断文件是否存在
            if (ncFile.isDirectory()) {
                System.out.println("2."+tempList[i]+"是文件夾");
            }
        }
    }

    /**
     * 新加功能FTP接收到的文件入库存储就行，但是这个入库跟云平台原来的入库不一样，不能移走文件，而且入库以后要实时监控各级产品到报情况，相当于把这个业务监控做到云平台里面，另外，就是多加一个功能，就是实现各级产品的加载显示
     * @param filePath
     * @param ncFile
     */
    void NcautoFile(String filePath, final File ncFile){
        //归档服务器路径是 win 还是 linux
        String archive = (String) YamlUtil.loadYaml("sysConfig.yaml").get("archive");
        // 指定源文件路径
        String sourceFilePath = filePath+"/"+ncFile.getName();
        // 指定目标文件夹路径
        //String targetFolderPath = "/opt/data/MarineFCST/";
        String targetFolderPath = "";
        if(archive.equals("win")) {
            String pDir = configService.selectConfigByKey("gdwinpathh");
            targetFolderPath = pDir;
        }else{
            String pDir = configService.selectConfigByKey("gdlinuxpathh");
            targetFolderPath = pDir;
        }
        //目录名称
        String mlName = "";
        //目录级别
        String Lnum = "";
        //Value
        String value = "";
        String[] s = ncFile.getName().split("_");
        //查询二级产品
        List<ONCfileMenu> list =  onCfilemeunService.getcp();
        for (int i = 0; i < list.size(); i++) {
            if(ncFile.getName().contains(list.get(i).getValue())){
                value = list.get(i).getValue();
                targetFolderPath += s[0]+"/"+s[1]+"/"+s[2]+"/"+s[3];
                mlName = list.get(i).getName();
                Lnum = ifLnum(ncFile);
            }
        }
        /*if(ncFile.getName().contains("L0") || ncFile.getName().contains("L4") || ncFile.getName().contains("L5")){
            //预报中心目录
            //targetFolderPath += "NMF/china_seas/whole/NMF_BEN_DT_CS_grid";
            targetFolderPath += s[0]+"/"+s[1]+"/"+s[2]+"/"+s[3];
            mlName = "预报中心";
            Lnum = ifLnum(ncFile);
        }else if(ncFile.getName().contains("L1")){
            //浙江省台目录
            //targetFolderPath += "PZJ/china_seas/ZJS/PZJ_BEN_DT_CS_grid";
            targetFolderPath += s[0]+"/"+s[1]+"/"+s[2]+"/"+s[3];
            mlName = "浙江省台";
            Lnum = ifLnum(ncFile);
        }else if(ncFile.getName().contains("L2") || ncFile.getName().contains("L3")){
            //东海区台目录
            //targetFolderPath += "REF/china_seas/DHDT/REF_BEN_DT_CS_grid";
            targetFolderPath += s[0]+"/"+s[1]+"/"+s[2]+"/"+s[3];
            mlName = "东海区台";
            Lnum = ifLnum(ncFile);
        }*/
        //创建文件夹
        File folder = new File(targetFolderPath);
        if(!folder.exists()){
            boolean success = folder.mkdirs();
            if (success) {
                System.out.println("文件夹创建成功");
            } else {
                //addLog(ncFile.getName()+"--智能网格--创建归档文件夹失败---创建的路径"+targetFolderPath);
            }
        }

        try {
            // 将路径转换为 Path 对象
            Path sourcePath = Paths.get(sourceFilePath);
            Path targetPath = Paths.get(targetFolderPath).resolve(sourcePath.getFileName());
            System.out.println(sourcePath);
            //备份数据
            //beifenFile(filePath, "success", ncFile);
            LocalDate now = LocalDate.now();
            String format = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            File f = new File(filePath+"/success/"+format);//创建文件夹
            if(!f.exists()){
                boolean mkdirs = f.mkdirs();
                if(mkdirs==false){
                    //addLog(ncFile.getName()+"--智能网格--备份时创建文件夹失败--备份路径"+filePath+"/success/"+format);
                }
            }
            copy(ncFile, filePath+"/success/"+format+"/"+ncFile.getName());
            // 移动文件
            //Files.move(sourcePath, targetPath);
            //文件copy
            copy(ncFile, targetPath.toString());//归档到文件夹
            //移动成功保存到数据库
            oNcfileMonitor nc = new oNcfileMonitor();
            nc.setFilename(ncFile.getName());//文件名
           // String s = targetPath.toString();
            nc.setFilepath(targetPath.toString());//文件路径
            long size = Files.size(targetPath);
            //long length = ncFile.length();
            long fileSize = getFileSizes(ncFile);
            BigDecimal fileSizeM = new BigDecimal(fileSize / 1024.0 / 1024.0).setScale(2, BigDecimal.ROUND_HALF_UP);
            logger.info("文件" + ncFile.getName() + "文件大小为：" + fileSizeM);
            /*BigDecimal bd = new BigDecimal(size / 1048576.0);
            bd = bd.setScale(2, RoundingMode.HALF_UP);*/
            nc.setFilesize(fileSizeM.toString()+"MB");//文件大小 //String.valueOf(ncFile.length())
            nc.setLjb(Lnum);//文件级别

            Date date = new Date();
            SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            nc.setRktime(date);//入库时间
            Calendar cal=Calendar.getInstance();
            nc.setRknf(String.valueOf(cal.get(Calendar.YEAR)));//入库年份
            nc.setRkyf(String.valueOf(cal.get(Calendar.MONTH)+1));//入库月份
            nc.setRkrq(String.valueOf(cal.get(Calendar.DATE)));//入库天
            nc.setRkjg(mlName);
            int b = oNcfileMonitorMapper.instdata(nc);
            if(b>0){
                //获取订阅单中是否有智能网格的订阅信息
                List<OWorkOrder> listznwg = ioWorkOrderService.selectZnwg(Config.ZNWG.getZnwg()+mlName);
                //如果有，智能网格自动发布
                if(listznwg.size()>0){
                    //循环订阅单信息，根据订阅单信息，插入到下载单列表，后期ftp推送使用
                    for (int i = 0; i < listznwg.size(); i++) {
                        //判断是否在订阅时间内
                        Date endDate = listznwg.get(i).getEndDate();//结束时间
                        Date beginDate = listznwg.get(i).getBeginDate();//开始时间
                        boolean dateInRange = isDateInRange(new Date(), beginDate, endDate);
                        if(dateInRange){//在订阅时间内
                            if(listznwg.get(i).getWorkType().equals("1")){//部分覆盖
                                try(NetCDFSource source  = new NetCDFSource(new File(targetPath.toString()))){

                                    String path = targetFolderPath+"cut_data/"+new SimpleDateFormat("yyyy年MM月dd日").format(date)+"/";
                                    File cf = new File(path);
                                    if (!cf.exists()) {//pa那段文件夹是否存在 不存在创建
                                        if (cf.mkdirs()) {//创建文件夹
                                            System.out.println("文件夹创建成功");
                                        } else {
                                            System.out.println("文件夹创建失败");
                                        }
                                    }



                                    NetCDFSourceExtractor copier = new NetCDFSourceExtractor(source,path+targetPath.getFileName());
                                    //LonLatBounds bounds = source.listAllLayer().get(0).getBounds();
                                    OWorkOrdernccj oWorkOrdernccjs = oWorkOrdernccjMapper.selectworkid(listznwg.get(i).getWorkCode());

                                    LonLatBounds bounds = new LonLatBounds(Double.parseDouble(oWorkOrdernccjs.getMinLon()),Double.parseDouble(oWorkOrdernccjs.getMaxLon()),Double.parseDouble(oWorkOrdernccjs.getMinLat()),Double.parseDouble(oWorkOrdernccjs.getMaxLat()));
                                    //左下角x坐标minLon   左下角y坐标minLat     右上角x坐标maxLon   右上角y坐标maxLat
                                    copier.extract(bounds,null);
                                    System.out.println("-------");
                                    String[] split = listznwg.get(i).getProductId().split("_");
                                    if(split[1].equals(value)) {//如果订阅单中的id中有value值 当前方法中的文件就是订阅单中需要推送的产品，将其添加到下载单中
                                        ODownOrder oDownOrder = new ODownOrder();
                                        oDownOrder.setId(UUID.randomUUID().toString());//id
                                        oDownOrder.setCreateDate(new Date());//时间
                                        oDownOrder.setResourcePath(targetPath.toString());//路径
                                        oDownOrder.setStatus("0");//状态
                                        oDownOrder.setWorkNo(listznwg.get(i).getWorkCode());//订阅单编号
                                        oDownOrder.setUserId(listznwg.get(i).getOrganization());//userid
                                        oDownOrder.setDepartId(listznwg.get(i).getDepartId());//部门id
                                        int i1 = ioDownOrderService.insertODownOrder(oDownOrder);//插入到下载单中
                                    }
                                }catch (Exception e){
                                    addAutoLog("文件"+ncFile.getName()+"裁剪失败，请检查文件", (short) 8, (short) 0);
                                }
                            }else{//全覆盖
                            String[] split = listznwg.get(i).getProductId().split("_");
                            if(split[1].equals(value)) {//如果订阅单中的id中有value值 当前方法中的文件就是订阅单中需要推送的产品，将其添加到下载单中
                                ODownOrder oDownOrder = new ODownOrder();
                                oDownOrder.setId(UUID.randomUUID().toString());//id
                                oDownOrder.setCreateDate(new Date());//时间
                                oDownOrder.setResourcePath(targetPath.toString());//路径
                                oDownOrder.setStatus("0");//状态
                                oDownOrder.setWorkNo(listznwg.get(i).getWorkCode());//订阅单编号
                                oDownOrder.setUserId(listznwg.get(i).getOrganization());//userid
                                oDownOrder.setDepartId(listznwg.get(i).getDepartId());//部门id
                                int i1 = ioDownOrderService.insertODownOrder(oDownOrder);//插入到下载单中
                            }
                            }

                        }else{
                            addAutoLog("文件"+ncFile.getName()+"不在订阅单id：["+listznwg.get(i).getId()+"]订阅时间内", (short) 8, (short) 0);
                            return;
                        }
                    }
                    ncFile.delete();//删除文件
                }

                //添加日志
                //addLog("文件"+ncFile.getName()+"归档成功");
                addAutoLog("文件"+ncFile.getName()+"归档成功", (short) 8, (short) 0);
                /*System.out.println("插入成功");
                ncFile.delete();//插入成功后删除文件
                TSLog log = new TSLog();
                log.setID(UUID.randomUUID().toString());
                log.setBroswer("后台自动归档");
                log.setLogcontent("文件"+ncFile.getName()+"归档成功");
                log.setLoglevel(8);
                log.setNote("-");
                log.setOperatetime(new Date());
                log.setOperatetype(3);
                tsLogMapper.insertTSLog(log);*/
            }
            System.out.println("文件移动成功！");
        } catch (Exception e) {
            //添加日志
            //addLog("文件"+ncFile.getName()+"归档失败。"+"文件移动失败: " + e.getMessage());
            addAutoLog("文件"+ncFile.getName()+"归档失败。"+"文件移动失败: " + e.getMessage(), (short) 8, (short) 0);
           /* TSLog log = new TSLog();
            log.setID(UUID.randomUUID().toString());
            log.setBroswer("后台自动归档");
            log.setLogcontent("文件"+ncFile.getName()+"归档失败。"+"文件移动失败: " + e.getMessage());
            log.setLoglevel(8);
            log.setNote("-");
            log.setOperatetime(new Date());
            log.setOperatetype(3);
            tsLogMapper.insertTSLog(log);
            System.err.println("文件移动失败: " + e.getMessage());*/
        }
    }

    String ifLnum(File file){
        String Lnum = "";
        if(file.getName().contains("L0")){
            Lnum = "L0";
        }else if(file.getName().contains("L1")){
            Lnum = "L1";
        }else if(file.getName().contains("L2")){
            Lnum = "L2";
        }else if(file.getName().contains("L3")){
            Lnum = "L3";
        }else if(file.getName().contains("L4")){
            Lnum = "L4";
        }else if(file.getName().contains("L5")){
            Lnum = "L5";
        }
        return Lnum;
    }

    /***
     * 归档方法
     * @param filePath
     * @param ncFile
     */
    void autoFile(String filePath, final File ncFile) {
        /**
         * 获取配置文件数据
         */
        //归档服务器路径是 win 还是 linux
        String archive = (String) YamlUtil.loadYaml("sysConfig.yaml").get("archive");
         //Boolean bl = false;
        // 查找该文件属于哪个产品的
        String content1 = ncFile.getName();
        //判断是否为win系统
       /* if(archive.equals("win")){
            bl = this.ifEnoughByTime("D:\\ncfile" + File.separator + content1);
        }else{//判断是否为linux系统
            bl = this.ifEnoughByTime(File.separator + "cloud" + File.separator + "ncfile" + File.separator + content1);
        }*/
        OProductRelease productReleaseEntity = new OProductRelease();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String productDateName = dateFormat.format(new Date());
        long fileSize = getFileSizes(ncFile);
        //判断是否上传完成
        if (fileSizeMap.containsKey(ncFile.getName())) {
            long fileSizeOld = fileSizeMap.get(ncFile.getName());
            if (fileSize != fileSizeOld) {
                logger.info("文件" + ncFile.getName() + "未上传完成");
                fileSizeMap.put(ncFile.getName(), fileSize);
                return;
            } else {
                logger.info("文件" + ncFile.getName() + "上传完成");
                fileSizeMap.remove(ncFile.getName());
            }
        } else {
            fileSizeMap.put(ncFile.getName(), fileSize);
            return;
        }

        // 判断文件是否已归档
        String content = ncFile.getName();
        ONcFile oNcFile = new ONcFile();
        oNcFile.setFileName(content);
        List<ONcFile> ncFiles = oNcFileMapper.selectONcFileList(oNcFile);
        for (int i = 0; i < ncFiles.size(); i++) {
            int i1 = oNcFileMapper.deleteONcFileById(ncFiles.get(i).getId());
            addAutoLog(ncFile.getName() + "已归过档。当前再次归档为补传，替换上一次文件", Globals.Log_Type_AUTO, (short)0);
        }
      /*  if (ncFiles.size() > 0) {
            logger.info(ncFile.getName() + "已归过档。");
            ncFile.delete();//如果归过档就删除
            addAutoLog(ncFile.getName() + "已归过档。", Globals.Log_Type_AUTO, Globals.Log_Leavel_ERROR);
            return;
        }*/
        //注释掉的是判断是否归过档，以注释掉

        logger.info("map里面文件数" + fileSizeMap.size());
        String[] fileNames = FileUtils.getNameNotSuffix(ncFile.getName()).split("_");

        //命名规则错误场合
        if (fileNames.length < 5) {
            //备份数据
            beifenFile(filePath, "fail", ncFile);
            //if (bl) {
                ncFile.delete();
            //}
            //记录错误日志
            addAutoLog("文件" + ncFile.getName() + "的命名规则错误。", Globals.Log_Type_AUTO, Globals.Log_Leavel_ERROR);
            //sendMail("文件" + ncFile.getName() + "的命名规则错误。", "");
            logger.info("文件" + ncFile.getName() + "的命名规则错误。");
            return;
        }

        String fileName = "";
   /*     if (fileNames.length == 7) {
            fileName = fileNames[0] + "_" + fileNames[1] + "_" + fileNames[2] + "_" + fileNames[3] + "_YYYYMMDDHH_" + fileNames[5] + "_" + fileNames[6];
        } else if (fileNames.length == 8) {
            fileName = fileNames[0] + "_" + fileNames[1] + "_" + fileNames[2] + "_" + fileNames[3] + "_YYYYMMDDHH_" + fileNames[5] + "_" + fileNames[6] + "_" + fileNames[7];
        } else if (fileNames.length == 9) {
            fileName = fileNames[0] + "_" + fileNames[1] + "_" + fileNames[2] + "_" + fileNames[3] + "_YYYYMMDDhhmm_" + fileNames[5] + "_" + fileNames[6] + "_" + fileNames[7] + "_" + fileNames[8];
        }*/
        //更换新的命名规则 前四个字段不变 上面注释为之前的规则

        fileName = IsPname(ncFile.getName(), fileNames[4]); //根据文件名还原产品命名规则
        String ncFileDate = "";
        //根据新的命名规则更给逻辑，获取文件名中的时间，观测文件命名中必须要有时间，否则报错
        ncFileDate = fileNames[4];

        final String ncFileDates = ncFileDate;
        logger.info("查找的文件名为" + fileName);
        //记录原始地址
        String sourceFilePath = filePath;
        //先备份
        filePath = filePath + File.separator + "replace" + File.separator + productDateName;
        logger.info("备份路径" + filePath);

        //查看对应订阅但
        //List<OProduct> products = productService.selectOProductList(p);
        int dotIndex = fileName.lastIndexOf('.');
        String substring = "";
        if (dotIndex == -1) {
            substring =fileName;
        }
        substring = fileName.substring(0, dotIndex);
        List<OProduct> products = productService.getnamegz(substring);//查询产品，产品一般前五位不可有重复数据
        if(products.size()<=0){
            beifenFile(filePath, "fail", ncFile);//未找到对应产品
            //生产一个产品出来
            productReleaseEntity.setId(IdUtils.simpleUUID());
            productReleaseEntity.setMetadataId("-1");
            productReleaseEntity.setNcFileId("-1");
            productReleaseEntity.setProductCode(UUID.randomUUID().toString());
            productReleaseEntity.setProductId("-1");
            productReleaseEntity.setProductName(productDateName);
            productReleaseEntity.setStatus(0);//为找到对应产品 异常
            productReleaseEntity.setCreateDate(new Date());
            productReleaseEntity.setIsDel(0);
            productReleaseEntity.setFileType("-1");
            productReleaseEntity.setDepartId("-1");
            int i = productReleaseService.insertOProductRelease(productReleaseEntity);

            //添加日志
            //addLog("文件"+ncFile.getName()+"归档失败。原因：检查该产品是否订阅，如已订阅请检查文件名["+ncFile.getName()+"]是否与订阅单中订阅中文件名规则类型一样，是否名称不同，该问题是因为根据文件名格式没有在订阅单表中查询到订阅的产品信息");
            addAutoLog("文件"+ncFile.getName()+"归档失败。原因：未在产品表中找到["+ncFile.getName()+"]格式的命名规则", (short) 8, (short) 0);
            ncFile.delete();
            return;
        }
        if (products != null && products.size() > 0) {
            if(products.size()!=1){
                String pn = "";
                for (int i = 0; i < products.size(); i++) {
                    pn = "["+products.get(i).getProductName()+"]";
                }
                beifenFile(filePath, "fail", ncFile);//找到多个对应产品，无法确定具体对应产品
                addAutoLog("文件"+ncFile.getName()+"归档失败。原因：找到多个对应产品，无法确定具体对应产品["+ncFile.getName()+"],找到多个产品"+pn, (short) 8, (short) 0);
                ncFile.delete();
                return;
            }
            OProduct product = products.get(0);
            // 观测文件直接解析不归档
            if (product.getFileType().equals("out") && product.getIsOpen() == 0) {
                final String previewFile = filePath;
                //开启新的线程进行读取文件
                new Thread() {
                    @Override
                    public void run() {
                        //备份数据
                        String newFilePath = beifenFile(previewFile, "outFile", ncFile);
                        ncFile.delete();//备份后删除
                        previewElementService.parsePreviewFile(new File(newFilePath), ncFileDates);
                    }
                }.start();
            }
            String fullFileName = FileUtils.getNameNotSuffix(ncFile.getName());//不替换名字
            String fileExtend = FileUtils.getExtend(ncFile.getName(), "");
            if (!fileExtend.equals(product.getFileType())) {
                //备份数据
                beifenFile(filePath, "fail", ncFile);
                //记录错误日志
                logger.info("产品名称：" + product.getProductName() + ",文件" + ncFile.getName() + "的文件格式：" + fileExtend + "和产品设定的文件格式:" + product.getFileType() + "不一致", product.getSendMail());
                //添加日志
                TSLog log = new TSLog();
                log.setID(UUID.randomUUID().toString());
                log.setBroswer("后台自动归档");
                log.setLogcontent("文件"+ncFile.getName()+"归档失败。"+"产品名称：" + product.getProductName() + ",文件" + ncFile.getName() + "的文件格式：" + fileExtend + "和产品设定的文件格式:" + product.getFileType() + "不一致");
                log.setLoglevel(8);
                log.setNote("-");
                log.setOperatetime(new Date());
                log.setOperatetype(3);
                tsLogMapper.insertTSLog(log);
                ncFile.delete();
                return;
            }
            //文件名称
            String ext = "." + product.getFileType();
            //查找NC模板
            String metadataId = null;
            OMetadata m = new OMetadata();
            m.setProductId(product.getId());
            List<OMetadata> metadataList = metadataService.selectOMetadataList(m);
            OMetadata metadata = null;
            if (CollectionUtils.isNotEmpty(metadataList)) {
                metadata = metadataList.get(0);
            }
            if (metadata != null) {
                metadataId = metadataList.get(0).getId();
            }
            OResources resources = resourcesService.selectOResourcesById(product.getResourcesId());
            //文件归档的路径
            //String path = resources.getResourcesDirPath();
            //新需求修改更改归档路径，按照文件名前四位进行路径进行归档
            String path="";
            if(archive.equals("win")){
                String pDir = configService.selectConfigByKey("gdwinpathh");
                 path = pDir+fileNames[0] + "/" + fileNames[1] + "/" + fileNames[2] + "/" + fileNames[3];
            }else{
                String pDir = configService.selectConfigByKey("gdlinuxpathh");
                 path = pDir+fileNames[0] + "/" + fileNames[1] + "/" + fileNames[2] + "/" + fileNames[3];  //Linux 配置
            }

            //检查一个字符串是否为空或仅包含空白字符
            if (StringUtils.isBlank(path)) {
                //备份数据
                beifenFile(filePath, "fail", ncFile);
                ncFile.delete();
                //记录错误日志
                //sendMail("产品名称：" + product.getProductName() + ",产品品类" + product.getProductName() + "所属的资源目录未指定物理路径", product.getSendMail());
                logger.info("产品名称：" + product.getProductName() + ",产品品类" + product.getProductName() + "所属的资源目录未指定物理路径", product.getSendMail());
                //addLog("文件"+ncFile.getName()+"归档失败。"+"产品名称：" + product.getProductName() + ",产品品类" + product.getProductName() + "所属的资源目录未指定物理路径");


            } else {
//            	fullFileName = fileNames[0] + "_" + fileNames[1] + "_" + fileNames[2] + "_" + fileNames[3] + "_" + ncFileDate + "_" + fileNames[5] + "_" + fileNames[6];
                logger.info("文件归档路径:" + path + File.separator + fullFileName + ext);
             /*   String isNewHeadParams = DictUtils.getDictLabel2("params", "IS_NEW_HEAD_PARAMS", "OFF");
                if ((metadata == null || "ON".equals(isNewHeadParams)) && "nc".equals(product.getFileType().toLowerCase())) {
                    //对NC头文件进行解析
                    try {
                        metadata = bulidMetadataEntity(product, sourceFilePath, fullFileName, productReleaseEntity, metadata);
                        metadataId = metadata.getId();
                    } catch (Exception e) {
                        //备份数据
//                        beifenFile(filePath, "fail", ncFile);
                        logger.info("头文件解析错误提示：" + e.toString());
                    }
                } else {
                    productReleaseEntity.setIsPreview(0);
                }*/
                //文件移动 MB
                BigDecimal fileSizeM = new BigDecimal(fileSize / 1024.0 / 1024.0).setScale(4, BigDecimal.ROUND_HALF_UP);
                logger.info("文件" + ncFile.getName() + "文件大小为：" + fileSizeM);

                BigDecimal modeSizeM = product.getFileSize();
                //上限大小
                BigDecimal maxFileSize = product.getMaxFileSize().multiply(modeSizeM).divide(new BigDecimal(100)).setScale(4, BigDecimal.ROUND_HALF_UP);
                maxFileSize = modeSizeM.add(maxFileSize);
                //下限大小
                BigDecimal minFileSize = product.getMinFileSize().multiply(modeSizeM).divide(new BigDecimal(100)).setScale(4, BigDecimal.ROUND_DOWN);
                minFileSize = modeSizeM.subtract(minFileSize);
                //默认为0
                BigDecimal defaultFileSize = new BigDecimal(0);

                /**
                 * 文件大小限制
                 */
                if (product.getIsOpenThreshold() == 1) {//判断是否启用大小限制
                    if (fileSizeM.compareTo(maxFileSize) == 1) {
                        //备份数据
                        beifenFile(filePath, "fail", ncFile);
                        addAutoLog("文件" + ncFile.getName() + "归档失败，文件超过设定大小最高值" + maxFileSize + "MB,文件大小为:" + fileSizeM + "MB", Globals.Log_Type_AUTO, Globals.Log_Leavel_INFO);
                        ncFile.delete();
                        //sendMail("【国家海洋预报云服务平台】《" + product.getProductName() + "》负责人您好，您的产品文件" + ncFile.getName() + "归档失败，原因：产品文件大小高于设定大小上限" + maxFileSize + "MB", product.getSendMail());
                        logger.info("【国家海洋预报云服务平台】《" + product.getProductName() + "》负责人您好，您的产品文件" + ncFile.getName() + "归档失败，原因：产品文件大小高于设定大小上限" + maxFileSize + "MB", product.getSendMail());
                        sendSuccessSmsA(product.getSmsTipPhone(), product.getProductName(), ncFile.getName(), product.getId(), product.getDepartId(), "高于", "上限" + maxFileSize + "MB");
                        return;
                    } else if (fileSizeM.compareTo(minFileSize) == -1) {
                        // 备份数据
                        beifenFile(filePath, "fail", ncFile);
                        addAutoLog("文件" + ncFile.getName() + "归档失败，文件小于设定大小最低值" + minFileSize + "MB,文件大小为:" + fileSizeM + "MB", Globals.Log_Type_AUTO, Globals.Log_Leavel_INFO);
                        ncFile.delete();
                        //sendMail("【国家海洋预报云服务平台】《" + product.getProductName() + "》负责人您好，您的产品文件" + ncFile.getName() + "归档失败，原因：产品文件小于低于设定大小下限" + minFileSize + "MB", product.getSendMail());
                        logger.info("【国家海洋预报云服务平台】《" + product.getProductName() + "》负责人您好，您的产品文件" + ncFile.getName() + "归档失败，原因：产品文件小于低于设定大小下限" + minFileSize + "MB", product.getSendMail());
                        sendSuccessSmsA(product.getSmsTipPhone(), product.getProductName(), ncFile.getName(), product.getId(), product.getDepartId(), "低于", "下限" + minFileSize + "MB");
                        return;
                    }
                } else {
                    if (product.getMinSize() != null) {
                        BigDecimal minSize = new BigDecimal(product.getMinSize()).setScale(2, BigDecimal.ROUND_HALF_UP);
                        if ((minSize.divide(new BigDecimal(1000))).subtract(fileSizeM).compareTo(defaultFileSize) == 1) {
                            // 备份数据
                            beifenFile(filePath, "fail", ncFile);
                            addAutoLog("文件" + ncFile.getName() + "归档失败，产品未启用阈值，文件小于最低限制大小" + minSize + "KB,文件大小为:" + fileSizeM + "MB", Globals.Log_Type_AUTO, Globals.Log_Leavel_INFO);
                            ncFile.delete();
                            //sendMail("【国家海洋预报云服务平台】《" + product.getProductName() + "》负责人您好，您的产品文件" + ncFile.getName() + "归档失败，原因：产品文件大小小于最低设定值" + minSize + "KB", product.getSendMail());
                            logger.info("【国家海洋预报云服务平台】《" + product.getProductName() + "》负责人您好，您的产品文件" + ncFile.getName() + "归档失败，原因：产品文件大小小于最低设定值" + minSize + "KB", product.getSendMail());
                            sendSuccessSmsB(product.getSmsTipPhone(), product.getProductName(), ncFile.getName(), product.getId(), product.getDepartId(), "小于", minSize + "KB", "低");
                            return;
                        }
                    }
                }
                try {
                    if(product.getFileType().equals("tar")){//判断是否为tar文件
                        if (product.getIsUnzip() == 1) {//是否需要解压进行归档
                            try (InputStream is = Files.newInputStream(new File(ncFile.getPath()).toPath());
                                 TarArchiveInputStream tarInput = new TarArchiveInputStream(is)) {

                                TarArchiveEntry entry;
                                while ((entry = tarInput.getNextTarEntry()) != null) {
                                    System.out.println();
                                    // 忽略目录条目
                                    if (entry.isDirectory()) {
                                        continue;
                                    }

                                    // 构造输出文件路径
                                    File outputFile = new File(path, entry.getName());//输出到归档路径
                                    System.out.println(outputFile.getName());
                                    // 确保输出文件的父目录存在
                                    outputFile.getParentFile().mkdirs();

                                    // 将条目内容写入文件
                                    try (FileOutputStream fos = new FileOutputStream(outputFile)) {
                                        byte[] buffer = new byte[4096];
                                        int len;
                                        while ((len = tarInput.read(buffer)) != -1) {
                                            fos.write(buffer, 0, len);
                                        }
                                        //设置权限
                                        if(!archive.equals("win")) {
                                            Set<PosixFilePermission> permissions = PosixFilePermissions.fromString("rw-r--r--");
                                            Files.setPosixFilePermissions(outputFile.toPath(), permissions);
                                            System.out.println("文件权限已设置为rw-r--r--");
                                        }

                                        //进行归档压缩包中的nc文件
                                        //保存nc文件记录
                                        ONcFile addNcFile = new ONcFile();
                                        addNcFile.setId(IdUtils.simpleUUID());
                                        addNcFile.setFileName(outputFile.getName());
                                        addNcFile.setFtpPath(path.replace("\\", "/"));
                                        addNcFile.setFilePath(path.replace("\\", "/"));
                                        addNcFile.setFileSize(fileSizeM);
                                        addNcFile.setProductId(product.getId());
                                        addNcFile.setoMetadataId(metadataId);
                                        addNcFile.setIsDel(0);
                                        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
                                        formatter.setLenient(false);
                                        //nc文件时间
                                        addNcFile.setCreateDate(formatter.parse(ncFileDate.substring(0, 8)));
                                        addNcFile.setUpdateDate(new Date());
                                        addNcFile.setDepartId(resources.getDepartId());
                                        oNcFileMapper.insertONcFile(addNcFile);
                                        //生产一个产品出来
                                        productReleaseEntity.setId(IdUtils.simpleUUID());
                                        productReleaseEntity.setMetadataId(metadataId);
                                        productReleaseEntity.setNcFileId(addNcFile.getId());
                                        productReleaseEntity.setProductCode(UUID.randomUUID().toString());
                                        productReleaseEntity.setProductId(product.getId());
                                        productReleaseEntity.setProductName(outputFile.getName());
                                            //判断是否为晚传===========================================================
                                            Integer lateTransmission = product.getLateTransmission();//晚传允许时间
                                        String wcsz = product.getWcsz();//晚传时间
                                        String zt = "";
                                        if(wcsz == null){
                                            productReleaseEntity.setStatus(1);//正常归档//
                                        }else {
                                            String[] split = wcsz.split(",");
                                            if (split.length > 1) {//等于1证明有两个晚传时间，那么一天会有两个以上的数据
                                                for (int i = 0; i < split.length; i++) {//循环配置
                                                    String[] split1 = split[i].split("_");
                                                    String substring1 = "";
                                                    if (fileNames[4].length() == 10) {
                                                        substring1 = fileNames[4].substring(fileNames[4].length() - 2, fileNames[4].length());//获取文件名中的小时
                                                    }
                                                    if (fileNames[4].length() == 12) {
                                                        substring1 = fileNames[4].substring(fileNames[4].length() - 4, fileNames[4].length() - 2);//获取文件名中的小时
                                                    }
                                                    if (split1[1].equals(substring1)) {
                                                        String getgdny = getgdny(split1[1]);
                                                        if (split1[0].equals("0")) {//如果是0 就查前一天
                                                            getgdny = getgdny1(split1[1]);
                                                        }
                                                        LocalDateTime timezh = timezh(getgdny);//文件时间
                                                        LocalDateTime now = LocalDateTime.now();//当前时间
                                                        // 检查目标时间是否在当前时间之前
                                                        if (timezh.isBefore(now)) {
                                                            System.out.println("timezh时间早于now当前时间.");
                                                            productReleaseEntity.setStatus(1);//正常归档//
                                                            zt = "归档成功";
                                                        } else {
                                                            zt = "晚传";
                                                            productReleaseEntity.setStatus(2);//晚传//
                                                        }
                                                    }
                                                }
                                            } else {
                                                LocalDateTime timezh = timezh(fileNames[4]);//文件时间
                                                if (lateTransmission != null) {
                                                    timezh = timezh.plusMinutes(lateTransmission);
                                                }
                                                LocalDateTime now = LocalDateTime.now();//当前时间
                                                // 检查目标时间是否在当前时间之前
                                                if (timezh.isBefore(now)) {
                                                    System.out.println("timezh时间早于now当前时间.");
                                                    productReleaseEntity.setStatus(1);//正常归档//
                                                    zt = "归档成功";
                                                } else {
                                                    zt = "晚传";
                                                    productReleaseEntity.setStatus(2);//晚传//
                                                }
                                            }
                                        }

                                        //=====================================================
                                        productReleaseEntity.setCreateDate(new Date());
                                        productReleaseEntity.setIsDel(0);
                                        productReleaseEntity.setFileType(product.getFileType());
                                        productReleaseEntity.setDepartId(resources.getDepartId());
                                        int i = productReleaseService.insertOProductRelease(productReleaseEntity);
                                        //查看是否自动发布
                                        if (product.getIsAuto() == 1) {
                                            String s = productReleaseService.releaseProduct(productReleaseEntity.getId());
                                            addAutoLog(s + zt, Globals.Log_Type_AUTO, Globals.Log_Leavel_INFO);
                                        }


                                    }
                                }
                            }
                        }else{
                            //保存nc文件记录
                            ONcFile addNcFile = new ONcFile();
                            addNcFile.setId(IdUtils.simpleUUID());
                            addNcFile.setFileName(ncFile.getName());
                            addNcFile.setFtpPath(path.replace("\\", "/"));
                            addNcFile.setFilePath(path.replace("\\", "/"));
                            addNcFile.setFileSize(fileSizeM);
                            addNcFile.setProductId(product.getId());
                            addNcFile.setoMetadataId(metadataId);
                            addNcFile.setIsDel(0);
                            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
                            formatter.setLenient(false);
                            //nc文件时间
                            addNcFile.setCreateDate(formatter.parse(ncFileDate.substring(0, 8)));
                            addNcFile.setUpdateDate(new Date());
                            addNcFile.setDepartId(resources.getDepartId());
                            oNcFileMapper.insertONcFile(addNcFile);
                            //生产一个产品出来
                            productReleaseEntity.setId(IdUtils.simpleUUID());
                            productReleaseEntity.setMetadataId(metadataId);
                            productReleaseEntity.setNcFileId(addNcFile.getId());
                            productReleaseEntity.setProductCode(UUID.randomUUID().toString());
                            productReleaseEntity.setProductId(product.getId());
                            productReleaseEntity.setProductName(ncFile.getName());
                            //判断是否为晚传
                         /*   Integer lateTransmission = product.getLateTransmission();//晚传允许时间
                            LocalDateTime timezh = timezh(fileNames[4]);//文件时间
                                if(lateTransmission != null){
                                    timezh = timezh.plusMinutes(lateTransmission);
                                }
                                LocalDateTime now = LocalDateTime.now();//当前时间
                                // 检查目标时间是否在当前时间之前
                                if (timezh.isBefore(now)) {
                                    System.out.println("timezh时间早于now当前时间.");
                                    productReleaseEntity.setStatus(1);//正常归档//
                                } else {
                                    productReleaseEntity.setStatus(2);//正常归档//
                                }*/
                            //判断是否为晚传===========================================================
                            Integer lateTransmission = product.getLateTransmission();//晚传允许时间
                            String wcsz = product.getWcsz();//晚传时间
                            String zt = "";
                            if(wcsz == null){
                                productReleaseEntity.setStatus(1);//正常归档//
                            }else {
                                String[] split = wcsz.split(",");
                                if (split.length > 1) {//等于1证明有两个晚传时间，那么一天会有两个以上的数据
                                    for (int i = 0; i < split.length; i++) {//循环配置
                                        String[] split1 = split[i].split("_");
                                        String substring1 = "";
                                        if (fileNames[4].length() == 10) {
                                            substring1 = fileNames[4].substring(fileNames[4].length() - 2, fileNames[4].length());//获取文件名中的小时
                                        }
                                        if (fileNames[4].length() == 12) {
                                            substring1 = fileNames[4].substring(fileNames[4].length() - 4, fileNames[4].length() - 2);//获取文件名中的小时
                                        }
                                        if (split1[3].equals(substring1)) {
                                            String getgdny = getgdny(split1[3]);
                                            if (split1[0].equals("0")) {//如果是0 就查前一天
                                                getgdny = getgdny1(split1[3]);
                                            }
                                            LocalDateTime timezh = timezh(getgdny);//文件时间
                                            LocalDateTime now = LocalDateTime.now();//当前时间
                                            // 检查目标时间是否在当前时间之前
                                            if (timezh.isBefore(now)) {
                                                System.out.println("timezh时间早于now当前时间.");
                                                productReleaseEntity.setStatus(1);//正常归档//
                                                zt = "归档成功";
                                            } else {
                                                zt = "晚传";
                                                productReleaseEntity.setStatus(2);//正常归档//
                                            }
                                        }
                                    }
                                } else {
                                    LocalDateTime timezh = timezh(fileNames[4]);//文件时间
                                    if (lateTransmission != null) {
                                        timezh = timezh.plusMinutes(lateTransmission);
                                    }
                                    LocalDateTime now = LocalDateTime.now();//当前时间
                                    // 检查目标时间是否在当前时间之前
                                    if (timezh.isBefore(now)) {
                                        System.out.println("timezh时间早于now当前时间.");
                                        productReleaseEntity.setStatus(1);//正常归档//
                                        zt = "归档成功";
                                    } else {
                                        zt = "晚传";
                                        productReleaseEntity.setStatus(2);//正常归档//
                                    }
                                }
                            }

                            //=====================================================
                            productReleaseEntity.setCreateDate(new Date());
                            productReleaseEntity.setIsDel(0);
                            productReleaseEntity.setFileType(product.getFileType());
                            productReleaseEntity.setDepartId(resources.getDepartId());
                            int i = productReleaseService.insertOProductRelease(productReleaseEntity);
                            //查看是否自动发布
                            if (product.getIsAuto() == 1) {
                                String s = productReleaseService.releaseProduct(productReleaseEntity.getId());
                                addAutoLog(s + zt, Globals.Log_Type_AUTO, Globals.Log_Leavel_INFO);
                            }
                            //归档之前判断归档目录是否存在
                            File file = new File(path);
                            if (!file.exists()) {
                                file.mkdirs();
                            }
                            //文件copy
                            copy(ncFile, path + File.separator + fullFileName + ext);
                            //设置权限
                            if(!archive.equals("win")) {
                                Set<PosixFilePermission> permissions = PosixFilePermissions.fromString("rw-r--r--");
                                Files.setPosixFilePermissions(new File(path + File.separator + fullFileName + ext).toPath(), permissions);
                                System.out.println("文件权限已设置为rw-r--r--");
                            }
                            //添加日志
                            addAutoLog("文件" + ncFile.getName() + "归档成功", Globals.Log_Type_AUTO, Globals.Log_Leavel_INFO);
                        }
                    }else{
                    ONcFile nf = new ONcFile();
                    nf.setFileName(fullFileName + ext);
                    List<ONcFile> ncFileList = oNcFileMapper.selectONcFileList(nf);
                    if (ncFileList.size() == 0) {
                        //保存nc文件记录
                        ONcFile addNcFile = new ONcFile();
                        addNcFile.setId(IdUtils.simpleUUID());
                        addNcFile.setFileName(fullFileName + ext);
                        addNcFile.setFtpPath(path.replace("\\", "/"));
                        addNcFile.setFilePath(path.replace("\\", "/"));
                        addNcFile.setFileSize(fileSizeM);
                        addNcFile.setProductId(product.getId());
                        addNcFile.setoMetadataId(metadataId);
                        addNcFile.setIsDel(0);
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
                        formatter.setLenient(false);
                        //nc文件时间
                        addNcFile.setCreateDate(formatter.parse(ncFileDate.substring(0, 8)));
                        addNcFile.setUpdateDate(new Date());
                        addNcFile.setDepartId(resources.getDepartId());
                        oNcFileMapper.insertONcFile(addNcFile);
                        //生产一个产品出来
                        productReleaseEntity.setId(IdUtils.simpleUUID());
                        productReleaseEntity.setMetadataId(metadataId);
                        productReleaseEntity.setNcFileId(addNcFile.getId());
                        productReleaseEntity.setProductCode(UUID.randomUUID().toString());
                        productReleaseEntity.setProductId(product.getId());
                        productReleaseEntity.setProductName(fullFileName);
                            //判断是否为晚传
                      /*      Integer lateTransmission = product.getLateTransmission();//晚传允许时间
                            LocalDateTime timezh = timezh(fileNames[4]);//文件时间
                            if(lateTransmission != null){
                                timezh = timezh.plusMinutes(lateTransmission);
                            }
                            LocalDateTime now = LocalDateTime.now();//当前时间
                            // 检查目标时间是否在当前时间之前
                            if (timezh.isBefore(now)) {
                                System.out.println("timezh时间早于now当前时间.");
                                productReleaseEntity.setStatus(2);//晚传归档//
                            } else {
                                productReleaseEntity.setStatus(1);//正常归档//
                            }*/
                        //判断是否为晚传===========================================================
                        Integer lateTransmission = product.getLateTransmission();//晚传允许时间
                        String wcsz = product.getWcsz();//晚传时间
                        String zt = "";
                        if(wcsz == null){
                            productReleaseEntity.setStatus(1);//正常归档//
                        }else {
                            String[] split = wcsz.split(",");
                            if (split.length > 1) {//大于1证明有两个晚传时间，那么一天会有两个以上的数据
                                for (int i = 0; i < split.length; i++) {//循环配置
                                    String[] split1 = split[i].split("_");
                                    String substring1 = "";
                                    if (fileNames[4].length() == 10) {
                                        substring1 = fileNames[4].substring(fileNames[4].length() - 2, fileNames[4].length());//获取文件名中的小时
                                    }
                                    if (fileNames[4].length() == 12) {
                                        substring1 = fileNames[4].substring(fileNames[4].length() - 4, fileNames[4].length() - 2);//获取文件名中的小时
                                    }
                                    if (split1[1].equals(substring1)) {
                                        String getgdny = getgdny(split1[1]);
                                        if (split1[0].equals("0")) {//如果是0 就查前一天
                                            getgdny = getgdny1(split1[1]);
                                        }
                                        LocalDateTime timezh = timezh(getgdny);//文件时间
                                        LocalDateTime now = LocalDateTime.now();//当前时间
                                        // 检查目标时间是否在当前时间之前
                                        if (timezh.isBefore(now)) {
                                            System.out.println("timezh时间早于now当前时间.");
                                            productReleaseEntity.setStatus(1);//正常归档//
                                            zt="归档成功";
                                        } else {
                                            zt="晚传";
                                            productReleaseEntity.setStatus(2);//正常归档//
                                        }
                                    }
                                }
                            } else {
                                LocalDateTime timezh = timezh(fileNames[4]);//文件时间
                                if (lateTransmission != null) {
                                    timezh = timezh.plusMinutes(lateTransmission);
                                }
                                LocalDateTime now = LocalDateTime.now();//当前时间
                                // 检查目标时间是否在当前时间之前
                                if (timezh.isBefore(now)) {
                                    System.out.println("timezh时间早于now当前时间.");
                                    productReleaseEntity.setStatus(1);//正常归档//
                                    zt="归档成功";
                                } else {
                                    productReleaseEntity.setStatus(2);//正常归档//
                                    zt="晚传";
                                }
                            }
                        }

                        //=====================================================
                        productReleaseEntity.setCreateDate(new Date());
                        productReleaseEntity.setIsDel(0);
                        productReleaseEntity.setFileType(product.getFileType());
                        productReleaseEntity.setDepartId(resources.getDepartId());
                        int i = productReleaseService.insertOProductRelease(productReleaseEntity);


                        //归档之前判断归档目录是否存在
                        File file = new File(path);
                        if (!file.exists()) {
                            file.mkdirs();
                        }
                        //文件copy
                        copy(ncFile, path + File.separator + fullFileName + ext);
                        //查看是否自动发布
                        if (product.getIsAuto() == 1) {
                            String s = productReleaseService.releaseProduct(productReleaseEntity.getId());
                            addAutoLog(s+zt, Globals.Log_Type_AUTO, Globals.Log_Leavel_INFO);
                        }
                        //设置权限
                        if(!archive.equals("win")) {
                            Set<PosixFilePermission> permissions = PosixFilePermissions.fromString("rw-r--r--");
                            Files.setPosixFilePermissions(new File(path + File.separator + fullFileName + ext).toPath(), permissions);
                        }
                        System.out.println("文件权限已设置为rw-r--r--");
                        //添加日志
                        addAutoLog("文件" + ncFile.getName() + "归档成功", Globals.Log_Type_AUTO, Globals.Log_Leavel_INFO);
                    }
                        //-------------------------------------------------------------解压-------------------------------------------------------------
                        //是否解压
                        /*if (product.getIsUnzip() == 1) {
                            //extractTarFile(filePath,);
//                            String inputFile = sourceFilePath + "\\" + content;
                            String inputFile = path + File.separator + fullFileName + ext;
                            String outFile = path + File.separator + "untarfiles" + File.separator + fullFileName + File.separator;
                            Map<String, String> map = new HashMap<>();
                            map.put("ext", ext);
                            map.put("inputFile", inputFile);
                            map.put("outFile", outFile);
                            map.put("productId", product.getId());
                            map.put("metadataId", metadataId);
                            map.put("ncFileDate", ncFileDate);
                            map.put("departId", resources.getDepartId());
                            map.put("ncFileId", addNcFile.getId());
                            map.put("releaseId", productReleaseEntity.getId());
                            String message = fileJar(map);
                            if ("success".equals(message)) {
                                logger.info("==============：" + "解压成功");
                                addAutoLog("文件" + ncFile.getName() + "解压成功", Globals.Log_Type_AUTO, Globals.Log_Leavel_INFO);
                            } else {
                               addAutoLog("文件" + ncFile.getName() + "解压失败", Globals.Log_Type_AUTO, Globals.Log_Leavel_ERROR);

                            }
                            //解压生成调用exe文件的xml
                            String xmlFile = createNcInputXML(addNcFile.getFilePath(), addNcFile.getFileName());
                            logger.info("xmlFile==============：" + xmlFile);
                            String xmlPath = DictUtils.getDictLabel2("params", "ncInputXmlPath", "/cloud/xml/input");
                            //先备份
                            File xmlPathFile = new File(xmlFile);
                            //判断文件夹是否存在,如果不存在则创建文件夹
                            if (xmlPathFile.exists()) {
                                beifenFile(xmlPath + "/backups/" + productDateName, "", xmlPathFile);
                            }
                            if (!"".equals(xmlFile)) {
                                //java程序位置：/cloud/exe/javaRunExe/ RunExe，exe程序位置：/cloud/exe/DataConvert/ConvertNC
                                String cmd = "java -cp /cloud/exe/javaRunExe/ RunExe /cloud/exe/DataConvert/ConvertNC " + xmlFile;
                                logger.info("执行命令==============：" + cmd);
                                try {
                                    Process process = Runtime.getRuntime().exec(cmd);
                                    Thread.sleep(1000 * 60 * 2);
                                    process.destroy();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    logger.info("读取exe错误信息：" + e.getMessage());
                                } finally {
                                }
                            }
                        }*/
                    }


                    //备份数据
                    beifenFile(filePath, "success", ncFile);
                    if (ncFile.exists()) {
                        ncFile.delete();
                    }
                } catch (Exception e) {
                    //备份数据
                    beifenFile(filePath, "fail", ncFile);
                    //记录错误日志
                    addAutoLog("文件" + ncFile.getName() + "归档失败,失败原因:" + e.getMessage(), Globals.Log_Type_AUTO, Globals.Log_Leavel_ERROR);
                    ncFile.delete();
                    //sendMail("产品名称：" + product.getProductName() + "文件" + ncFile.getName() + "归档失败,失败原因:" + e.getMessage(), product.getSendMail());
                    logger.info("产品名称：" + product.getProductName() + "文件" + ncFile.getName() + "归档失败,失败原因:" + e.getMessage(), product.getSendMail());
                } finally {
                    // 查询数据 多的删除留一条
                    ONcFile onf = new ONcFile();
                    onf.setFileName(fullFileName + ext);
                    List<ONcFile> ncFileEntities2 = oNcFileMapper.selectONcFileList(onf);
                    if (ncFileEntities2.size() > 1) {
                        for (int i = 1; i < ncFileEntities2.size(); i++) {
                            oNcFileMapper.deleteONcFileById(ncFileEntities2.get(i).getId());
                        }
                    }
                }
                //备份数据
                beifenFile(filePath, "success", ncFile);
                ncFile.delete();
            }
        } else {
            //备份数据
            beifenFile(filePath, "fail", ncFile);
            ncFile.delete();
            //记录错误日志
            logger.info("文件" + ncFile.getName() + "没有对应的产品品类");
            this.addAutoLog("文件" + ncFile.getName() + "没有对应的产品品类", Globals.Log_Type_AUTO, Globals.Log_Leavel_ERROR);
            // sendMail("文件" + ncFile.getName() + "没有对应的产品品类", "");
        }
    }

    /**
     * 查询文件上传时间
     * @param filename
     * @return
     */
    public Boolean ifEnoughByTime(String filename) {
        try {
            System.out.print("-------------文件路径---------" + filename + "-------------");
            File f = new File(filename);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar cal = Calendar.getInstance();
            cal.setTimeInMillis(f.lastModified());
            String time = sdf.format(cal.getTime());
            //开始时间
            Date begin = sdf.parse(time);
            System.out.print("----文件修改时间---------" + begin + "------------");
            //结束时间
            Date end = sdf.parse(sdf.format(new Date()));

            System.out.print("----文件现在时间---------" + end + "------------");

            long between = (end.getTime() - begin.getTime()) / 1000;//除以1000是为了转换成秒
            int day = new Long(between / (24 * 3600)).intValue();
            int hour = new Long(between % (24 * 3600) / 3600).intValue();
            int minute = new Long(between % 3600 / 60).intValue();
            if (day > 0 || hour > 2) {
                //true 移走或删除文件
                return true;
            } else {
                if (hour == 2 && minute >= 30) {
                    return true;
                } else {
                    return false;
                }
            }
        } catch (ParseException e) {
            addAutoLog("文件" + filename + "查询文件上传时间错误:" + e.getMessage(), Globals.Log_Type_OTHER, Globals.Log_Leavel_ERROR);
            return false;
        }
    }

    /**
     * 添加日志
     */

    public void addAutoLog(String logcontent, Short loglevel, Short operatetype) {
        logger.info("错误日志" + logcontent);
        TSLog log = new TSLog();
        log.setID(UUID.randomUUID().toString());
        log.setLogcontent(logcontent);
        log.setLoglevel(loglevel.intValue());
        log.setOperatetype(3);
        String ipAddress = "-";//request.getRemoteAddr();
        log.setNote(ipAddress);
        log.setBroswer("后台自动归档");
        log.setOperatetime(new Date());
//		log.setTSUser("系统自动");
        tsLogMapper.insertTSLog(log);
    }

    /**
     * 后改的添加日志方法，上面的也在用
     * @param logcontent
     */
    public void addLog(String logcontent) {
        TSLog log = new TSLog();
        log.setID(UUID.randomUUID().toString());
        log.setBroswer("后台自动归档");
        log.setLogcontent(logcontent);
        log.setLoglevel(8);
        log.setNote("-");
        log.setOperatetime(new Date());
        log.setOperatetype(3);
        tsLogMapper.insertTSLog(log);
    }



    /**
     * 获取文件大小
     */
    public long getFileSizes(File f) {
        //取得文件大小
        long s = 0;
        if (f.exists() && f.isFile()) {
            s = f.length();
            logger.info("file length ：" + s);
        } else {
            logger.info("file doesn't exist or is not a file");
        }

        return s;
    }

    /**
     * 备份文件
     *
     * @param filePath 文件路径
     * @param fileName 成功还是失败归档
     * @param ncFile   文件
     */
    public String beifenFile(String filePath, String fileName, File ncFile) {
        filePath = filePath.replace("replace", fileName);
        File fileCopy = new File(filePath);
        //判断文件夹是否存在,如果不存在则创建文件夹
        if (!fileCopy.exists()) {
            fileCopy.mkdirs();
        }
        copy(ncFile, filePath + "/" + ncFile.getName());
        return filePath + "/" + ncFile.getName();
    }

    public static void copy(File oldfile, String newPath) {
        InputStream inStream = null;
        FileOutputStream fs = null;
        try {
            int bytesum = 0;
            int byteread = 0;
            boolean exists = oldfile.exists();
            if (oldfile.exists()) {
                inStream = new FileInputStream(oldfile);
                fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread;
                    fs.write(buffer, 0, byteread);
                }

            }
        } catch (Exception e) {
            //addLog(oldfile.getName()+"--智能网格-- 复制到归档文件夹失败");
            e.printStackTrace();
        } finally {
            try {
                if (inStream != null) {
                    inStream.close();
                }
                if (fs != null) {
                    fs.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 发送邮件
     */
    @Override
    public void sendMail(String content, String receiver) {
        String smtpHost = DictUtils.getDictLabel2("params", "smtpHost", "smtp.163.com");
        String copyUsers = DictUtils.getDictLabel2("params", "copyUser", "hyybypt@163.com");
        String sender = DictUtils.getDictLabel2("params", "sender", "ybzx_cloud@163.com");
        String pwd = DictUtils.getDictLabel2("params", "pwd", "YBZX@abc");
        //接收人为空场合
        if (StringUtils.isEmpty(receiver)) {
            receiver = DictUtils.getDictLabel2("params", "receiver", "ybzx_cloud@163.com");
        }
        try {
            this.sendSuEmail(smtpHost, receiver, copyUsers, "归档异常",
                    content, sender,
                    sender, pwd);
        } catch (Exception e) {
            String remark = "";
            if (e instanceof AuthenticationFailedException) {
                remark = "认证失败错误的用户名或者密码";
            } else if (e instanceof SMTPAddressFailedException) {
                remark = "接受邮箱格式不对";
            } else if (e instanceof ConnectException) {
                remark = "邮件服务器连接失败";
            } else {
                remark = e.getMessage();
            }
//            this.addAutoLog("邮件发送失败,失败原因：" + remark, Globals.Log_Type_AUTO, Globals.Log_Leavel_ERROR);
        }
    }

    /**
     * 检查exe转换完成的xml文件
     */
    @Override
    public void checkNCXml() {
        try {
            String path = DictUtils.getDictLabel2("params", "ncOutputXmlPath", "/cloud/xml/output");
            File file = new File(path);
            File[] tempList = file.listFiles();
            if (tempList == null) {
                return;
            }
            for (int i = 0; i < tempList.length; i++) {
                File ncXmlFile = tempList[i];
                if (ncXmlFile.isFile()) {
                    //读取某个文件夹下的所有文件
                    System.out.println("文件：" + tempList[i]);
                    parsingNCXml(path, ncXmlFile);
                }
                if (ncXmlFile.isDirectory()) {
                    //读取某个文件夹下的所有文件夹
                    System.out.println("文件夹：" + tempList[i]);
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public ForeResult getNcFile(String productId, int currentPage) {
        ForeResult foreResult = new ForeResult();
        int pageSize = FILE_PAGESIZE;
        int start = (currentPage - 1) * pageSize;
        int count = oNcFileMapper.getCount(productId);
        List<Map> list = oNcFileMapper.ncFileSql(productId, start, pageSize);
        if (list.size() == 0) {
            foreResult.setResult("fail");
            foreResult.setTotalData(0);
        } else {
            foreResult.setResult("success");
            foreResult.setTotalData(list.size());
            foreResult.setMap(list);
            foreResult.setCurrentPage(currentPage);
            int pageCount = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
            foreResult.setPageCount(pageCount);
            foreResult.setPageSize(pageSize);
        }
        return foreResult;
    }

    @Override
    public List<ONcFile> getNcFile(String productId, Date date) {
        ONcFile ncFile = new ONcFile();
        ncFile.setProductId(productId);
        ncFile.setCreateDate(date);
        return oNcFileMapper.selectONcFileList(ncFile);
    }

    @Override
    public List<String> getNcFileDate(String productId) {
        return oNcFileMapper.getNcFileDateList(productId);
    }

    @Override
    public String download(String fileId, String productId) {
        ONcFile ncFile = oNcFileMapper.selectONcFileById(fileId);
        ODownLog downLog = new ODownLog();
        downLog.setDownTime(new Date());
        downLog.setProductId(productId);
        SysUser sysUser = ShiroUtils.getSysUser();
        downLog.setUserId("");
        if (sysUser != null)
            downLog.setUserId(sysUser.getUserId().toString());
        downLogService.insertODownLog(downLog);
        String path = ncFile.getFilePath() + "/" + ncFile.getFileName();
        return path;
    }

    @Override
    public AjaxResult createXmlFile(PreviewData previewData) {
        ONcFile ncFile = oNcFileMapper.selectONcFileById(previewData.getNcFileId());
        int mathNum = (int) ((Math.random() * 9 + 1) * 100000);
        String tempPath = DictUtils.getDictLabel2("params", "TEMP_URL", "/cloud/temp");
        //输出文件夹
        String outDirPath = tempPath + "/" + FileUtils.getNameNotSuffix(ncFile.getFileName()) + "_" + mathNum;
        File outDir = new File(outDirPath);
        //文件夹不存在场合
        if (!outDir.exists()) {
            outDir.mkdir();
        }
        System.out.println(outDir.getPath());
        System.out.println(outDir.getAbsolutePath());

        //xml文件
        final String xmlFile = outDirPath + "/" + FileUtils.getNameNotSuffix(ncFile.getFileName()) + "_" + mathNum + ".xml";
        //命令日志文件
        final String logPath = outDirPath + "/" + FileUtils.getNameNotSuffix(ncFile.getFileName()) + "_" + mathNum + "_log.txt";
//        final String xmlFile = "E://" + mathNum + ".xml";
        try {
            String xmlResultPath = BuildXMLDoc(ncFile, previewData, xmlFile, outDirPath, mathNum);
            // 调用生成图片接口
            logger.info("将要执行的画图命令：ips_Nco_Draw_Image_2S " + xmlFile + " >" + logPath);
            try {
                //开启子线程执行画图命令
                ExecutorService executorService = Executors.newFixedThreadPool(3);
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            logger.info("执行：ips_Nco_Draw_Image_2S开始");
                            //调用画图程序
                            String message = ExecLinuxCMDUtils.exec("ips_Nco_Draw_Image_2S " + xmlFile + " >" + logPath);
                            logger.info("执行：ips_Nco_Draw_Image_2S结束， 执行后的结果:" + message);

                        } catch (Exception e) {
                            logger.info("执行图片生成程序报错,错误：" + e.getMessage());
                            e.printStackTrace();
                        }
                    }
                });

                //预览结果
                int waitTime = Integer.parseInt(DictUtils.getDictLabel2("params", "WAIT_SECONDS_TIME", "30"));
                //是否有预览结果
                boolean isPreviewResult = false;
                long previewResultStartTime = System.currentTimeMillis();
                File file = null;

                //自定义等待60S 如果有结果则退出循环
                while (customerWait(previewResultStartTime, waitTime) && !isPreviewResult) {
                    file = new File(xmlResultPath);
                    //预览结果文件存在场合
                    if (file.exists()) {
                        isPreviewResult = true;
                    }
                }

                logger.info("主程序继续执行。");
                //文件不存在场合
                if (file == null || !isPreviewResult) {
                    return AjaxResult.error("生成图片失败。");
                } else {
                    String imageUrl = DictUtils.getDictLabel2("params","IMAGE_URL", "http://139.224.7.1:8080/");
                    imageUrl = imageUrl + outDirPath.replaceAll(tempPath, "") + "/";
                    SAXBuilder saxBuilder = new SAXBuilder();
                    InputStream in = new FileInputStream(file);
                    Document document = saxBuilder.build(in);
                    Element rootElement = document.getRootElement();
                    Element resultElement = rootElement.getChild("result");
                    String result = resultElement.getValue();

                    logger.info("结果result：" + result);
                    result = "success";

                    //成功场合
                    if ( "success".equals(result)) {
                        Element fileListElement = rootElement.getChild("FileList");
                        Element fileNameElement = fileListElement.getChild("FileName");
                        String imageName = fileNameElement.getValue();
                        //String imageName = "myimg.jpg";
                        File imageFile = new File(outDirPath + "/" + imageName);
                        logger.info("图片物理路径：" + outDirPath + "/" + imageName);

                        long previewImageStartTime = System.currentTimeMillis();
                        boolean isPreviewImage = false;
                        //自定义等待60S 如果有结果则退出循环
                        while (customerWait(previewImageStartTime, waitTime) && !isPreviewImage) {
                            //预览结果图片存在场合
                            if (imageFile.exists()) {
                                isPreviewImage = true;
                            }
                        }

                        if (imageFile.exists()) {
                            logger.info("图片路径：" + imageUrl);
                            return  AjaxResult.success(imageUrl + imageName);
                        } else {
                            logger.error("图片路径不存在图片。");
                            return AjaxResult.error("生成图片失败。");
                        }
                    }
                    //失败场合
                    else {
                        return  AjaxResult.error("生成图片失败。");
                    }
                }
            } catch (Exception e) {
                logger.info("执行调用图片生成接口报错,错误：" + e.getMessage());
                e.printStackTrace();
                return AjaxResult.error("生成图片失败。");
            }
        } catch (IOException e) {
                e.printStackTrace();
            return AjaxResult.error("生成图片失败。");
        } catch (JDOMException e) {
            e.printStackTrace();
            return AjaxResult.error("生成图片失败。");
        }
    }

    @Override
    public oNcfileMonitor getncZnwgdata(Integer fileid) {
        return oNcFileMapper.getncZnwgdata(fileid);
    }

    /**
     * 自定义是否等待
     *
     * @param startBeginTime 开始等待时间
     * @param waiTimeSeconds 等待的时间
     * @return
     */
    private boolean customerWait(long startBeginTime, int waiTimeSeconds) {
        long currentTime = System.currentTimeMillis();
        if ((currentTime - startBeginTime) / 1000 < waiTimeSeconds) {
            return true;
        }
        return false;
    }

    public OMetadata bulidMetadataEntity(OProduct product, String ncFilePath, String fileName, OProductRelease productReleaseEntity, OMetadata metadataEntity) throws Exception {
        //nc文件默认可预览
        productReleaseEntity.setIsPreview(1);
        OMetadata metadata = new OMetadata();
        metadata.setId(IdUtils.simpleUUID());
        try {
            //执行识别头文件命令 对nc文件进行自动识别
            //记录头文件存储路径
            String headerFilePath = DictUtils.getDictLabel2("params", "HEADER_FILE_PATH", "/cloud/nchead");
            String ncHeadPath = headerFilePath + "/" + fileName + ".txt";
            ncFilePath = ncFilePath + "/" + fileName + ".nc";
            //解析头文件
            identifyNcFile(ncFilePath, ncHeadPath);
            //解析识别头文件程序 识别出的文件
            String headInfo = readTxtFile(ncHeadPath);
            if (metadataEntity == null) {
                metadata.setProductId(product.getId());
                metadata.setResourcesId(product.getResourcesId());

                // 添加之前 在判断一下是否有数据   不知道数据库为啥重复  在加一层判断
                OMetadata query = new OMetadata();
                query.setProductId(product.getId());
                List<OMetadata> list = metadataService.selectOMetadataList(query);
                if (CollectionUtils.isNotEmpty(list) && list.get(0) != null) {
                    metadataService.insertOMetadata(metadata);
                }
            } else {
                metadata = metadataEntity;
                //删除老的参数
                metadataElementService.deleteOMetadataElementByMetadataId(metadataEntity.getId());
            }
            String[] yaosuList = headInfo.split(";");
            for (String yaosu : yaosuList) {
                OMetadataElement metadataElement = new OMetadataElement();
                metadataElement.setId(IdUtils.simpleUUID());
                String[] valueList = yaosu.split(":");
                if (valueList.length < 2) {
                    continue;
                }
                String elementEn = valueList[0];
                Integer valueCount = Integer.parseInt(valueList[1]);
                if (valueCount == -1) {
                    metadataElement.setElementRange("[-1,-1]");
                    metadataElement.setMaxValue(-1.0);
                    metadataElement.setMinValue(-1.0);
                    metadataElement.setSpan(-1.0);
                    metadataElement.setMetadataId(metadata.getId());
                    metadataElement.setElementEn(elementEn);
                    metadataElement.setElementZh(chineseName(elementEn));
                    metadataElement.setValueCount(valueCount);
                    metadataElement.setIsOutParameter("0");
                    metadataElement.setCreateDate(DateUtils.getNowDate());
                    metadataElementService.insertOMetadataElement(metadataElement);
                } else {
                    logger.info("要素名称：" + valueList[0]);
                    logger.info("值个数" + valueList[1]);
                    logger.info("要素值：" + valueList[2]);
                    logger.info("是否输出参数：" + valueList[3]);
                    //取出值的最大值，最小值
                    if (valueCount > 0) {
                        metadataElement = getMaxAndMinValue(metadataElement, valueList[2]);
                    }
                    metadataElement.setMetadataId(metadata.getId());
                    metadataElement.setElementEn(elementEn);
                    metadataElement.setElementZh(chineseName(elementEn));
                    metadataElement.setValueCount(valueCount);
                    metadataElement.setCreateDate(DateUtils.getNowDate());
                    metadataElement.setIsOutParameter(valueList[3]);
                    metadataElementService.insertOMetadataElement(metadataElement);
                }
            }
        } catch (Exception e) {
            metadataService.deleteOMetadataById(metadata.getId());
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
        return metadata;
    }

    //执行liunx命令 进行头文件识别
    public void identifyNcFile(String ncFilePath, String ncHeadPath) throws Exception {
        logger.info("解析的文件：" + ncFilePath + ",文件名：" + ncHeadPath);
//        String[] cmd = {"/bin/sh", "-c", "ips_NCO_GetHeadInfo_2S " + ncFilePath + " " + ncHeadPath};
        String[] cmd = {"/bin/sh", "-c", "ips_NCO_GetHeadInfo_2S_new " + ncFilePath + " " + ncHeadPath};
        String message = runCommand(cmd, -1);
        logger.info("执行：cd /home/yun_admin/bin" + " 执行后的结果:" + message);
    }

    /**
     * 执行shell命令
     * String[] cmd = { "sh", "-c", "lsmod |grep linuxVmux" }或者
     * String[] cmd = { "sh", "-c", "./load_driver.sh" }
     * int tp = 1 返回执行结果  非1 返回命令执行后的输出
     *
     * @throws Exception
     */
    public String runCommand(String[] cmd, int tp) throws Exception {
        StringBuffer buf = new StringBuffer(1000);
        String rt = "-1";
        Process pos = Runtime.getRuntime().exec(cmd);
        pos.waitFor();
        if (tp == 1) {
            if (pos.exitValue() == 0) {
                rt = "1";
            }
        } else {
            InputStreamReader ir = new InputStreamReader(pos.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            String ln = "";
            while ((ln = input.readLine()) != null) {
                buf.append(ln + "<br>");
            }
            rt = buf.toString();
            input.close();
            ir.close();
        }
        return rt;
    }

    public static String readTxtFile(String filePath) {
        StringBuilder sb = new StringBuilder();
        InputStreamReader read = null;
        BufferedReader bufferedReader = null;
        try {
            String encoding = "UTF-8";
            File file = new File(filePath);
            if (file.isFile() && file.exists()) { //判断文件是否存在
                read = new InputStreamReader(new FileInputStream(file), encoding);//考虑到编码格式
                bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    sb.append(lineTxt);
                }
                return sb.toString();
            } else {
                System.out.println("找不到指定的文件");
                throw new RuntimeException("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        } finally {
            if (read != null) {
                try {
                    read.close();
                } catch (IOException e) {
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                }
            }
        }
        return "";
    }


    // 已启用阈值
    public void sendSuccessSmsA(String iphones, String productname, String fileName, String productId, String deptId, String than, String modeSizeM) {
        String templateCode = "SMS_216826457";
        String templateParam = "{\"productname\":\"" + productname + "\",\"filename\":\"" + fileName + "\",\"than\":\"" + than + "\",\"modeSizeM\":\"" + modeSizeM + "\"}";
        boolean flag = false;
        boolean result = false;
        //多个电话配置
        if (iphones.contains(",")) {
            String[] phoneNumbers = iphones.split(",");
            for (String phoneNumber : phoneNumbers) {
                result = SendSms(getAccessKeyId(), getAccessSecret(), getRegionid(), phoneNumber, getSignName(), templateCode, templateParam);
                //多条发送有一条成功就视为成功
                if (result) {
                    flag = true;
                }
            }
        } else {
            flag = SendSms(getAccessKeyId(), getAccessSecret(), getRegionid(), iphones, getSignName(), templateCode, templateParam);
        }
        OProductCheckSms productCheckSms = new OProductCheckSms();
        productCheckSms.setProductId(productId);
        productCheckSms.setFileName(fileName);
        productCheckSms.setDepartId(deptId);
        productCheckSms.setCreateDate(new Date());
        productCheckSms.setTipTypes(0);
        productCheckSms.setSmsSendStatusContent(flag == true ? "归档提醒发送成功" : "归档提醒发送失败");
        productCheckSmsService.insertOProductCheckSms(productCheckSms);
        // addAutoLog("文件" + fileName + "归档提醒短信发送成功", Globals.Log_Type_AUTO, Globals.Log_Leavel_INFO);
    }

    // 未启用阈值
    public void sendSuccessSmsB(String iphones, String productname, String fileName, String productId, String deptId, String than, String modeSizeM, String level) {
        String templateCode = "SMS_216826458";
        String templateParam = "{\"productname\":\"" + productname + "\",\"filename\":\"" + fileName + "\",\"level\":\"" + level + "\",\"than\":\"" + than + "\",\"modeSizeM\":\"" + modeSizeM + "\"}";
        boolean flag = false;
        boolean result = false;
        //多个电话配置
        if (iphones != null) {
            if (iphones.contains(",")) {
                String[] phoneNumbers = iphones.split(",");
                for (String phoneNumber : phoneNumbers) {
                    result = SendSms(getAccessKeyId(), getAccessSecret(), getRegionid(), phoneNumber, getSignName(), templateCode, templateParam);
                    //多条发送有一条成功就视为成功
                    if (result) {
                        flag = true;
                    }
                }
            } else {
                flag = SendSms(getAccessKeyId(), getAccessSecret(), getRegionid(), iphones, getSignName(), templateCode, templateParam);
            }
        }
        OProductCheckSms productCheckSms = new OProductCheckSms();
        productCheckSms.setProductId(productId);
        productCheckSms.setFileName(fileName);
        productCheckSms.setDepartId(deptId);
        productCheckSms.setCreateDate(new Date());
        productCheckSms.setTipTypes(0);
        productCheckSms.setSmsSendStatusContent(flag == true ? "归档提醒发送成功" : "归档提醒发送失败");
        productCheckSmsService.insertOProductCheckSms(productCheckSms);
    }

    public boolean SendSms(String accessKeyId, String accessSecret, String regionid, String phoneNumbers, String signName, String templateCode, String templateParam) {
        DefaultProfile profile = DefaultProfile.getProfile(regionid, accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);

        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", regionid);
        request.putQueryParameter("PhoneNumbers", phoneNumbers);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", templateParam);
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ClientException e) {
            System.out.println(e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 创建xml
     *
     * @param filePath
     * @param fileName
     */
    public String createNcInputXML(String filePath, String fileName) {
        try {
            // 创建解析器工厂
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();
            org.w3c.dom.Document document = db.newDocument();
            // 不显示standalone="no"
            document.setXmlStandalone(true);
            org.w3c.dom.Element gribtoNCInfo = document.createElement("GribtoNCInfo");
            org.w3c.dom.Element inputFile = document.createElement("InputFile");
            inputFile.setTextContent(filePath + "/" + fileName);
            //输出位置
            String ncOutputXmlPath = DictUtils.getDictLabel2("params", "ncOutputXmlPath", "/cloud/xml/output");
            String fullFileName = FileUtils.getNameNotSuffix(fileName);//不替换名字
            final String ext = ".xml";
            String xmlOutPath = ncOutputXmlPath + "/" + fullFileName + ext;
            //创建xml输出文件夹
            File outputXmlFile = new File(ncOutputXmlPath);
            //判断文件夹是否存在,如果不存在则创建文件夹
            if (!outputXmlFile.exists()) {
                outputXmlFile.mkdirs();
            }
            //OutXmlFileName节点解析
            org.w3c.dom.Element outXmlFileName = document.createElement("OutXmlFileName");
            outXmlFileName.setTextContent(xmlOutPath);
            // 将book节点添加到bookstore根节点中
            gribtoNCInfo.appendChild(inputFile);
            gribtoNCInfo.appendChild(outXmlFileName);
            document.appendChild(gribtoNCInfo);
            // 创建TransformerFactory对象
            TransformerFactory tff = TransformerFactory.newInstance();
            // 创建 Transformer对象
            Transformer tf = tff.newTransformer();
            // 输出内容是否使用换行
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            // 创建xml文件并写入内容
            String ncInputXmlPath = DictUtils.getDictLabel2("params", "ncInputXmlPath", "/cloud/xml/input");
            String inputPath = ncInputXmlPath + "/" + fullFileName + ext;
            //创建xml输入文件夹
            File inputXmlFile = new File(ncInputXmlPath);
            //判断文件夹是否存在,如果不存在则创建文件夹
            if (!inputXmlFile.exists()) {
                inputXmlFile.mkdirs();
            }
            tf.transform(new DOMSource(document), new StreamResult(new File(inputPath)));
            return inputPath;
        } catch (Exception e) {
            e.printStackTrace();
//            addAutoLog("文件" + fileName + "生成.xml失败:" + e.getMessage(), Globals.Log_Type_AUTO, Globals.Log_Leavel_INFO);
            return "";
        }
    }

    /**
     * 解析xml
     *
     * @param filePath
     * @param ncXmlFile
     */
    public void parsingNCXml(String filePath, final File ncXmlFile) {
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
            String productDateName = dateFormat.format(new Date());
            //文件名
            String[] fileNames = FileUtils.getNameNotSuffix(ncXmlFile.getName()).split("_");
            //小于7位错误
            if (fileNames.length < 7) {
                //删除文件
                beifenFile(filePath, "fail", ncXmlFile);
                //记录错误日志
//                addAutoLog("文件" + ncXmlFile.getName() + "解析失败,命名规则有误", Globals.Log_Type_AUTO, Globals.Log_Leavel_ERROR);
                ncXmlFile.delete();
                return;
            }
            //创建文件规范名
            String fileName = "";
           /* if (fileNames.length == 7) {
                fileName = fileNames[0] + "_" + fileNames[1] + "_" + fileNames[2] + "_" + fileNames[3] + "_YYYYMMDDHH_" + fileNames[5] + "_" + fileNames[6];
            } else if (fileNames.length == 8) {
                fileName = fileNames[0] + "_" + fileNames[1] + "_" + fileNames[2] + "_" + fileNames[3] + "_" + fileNames[4] + "_YYYYMMDDHH_" + fileNames[6] + "_" + fileNames[7];
            }*/
            fileName = IsPname(ncXmlFile.getName(), fileNames[4]);//命名规范
            //文件名字去后缀，如：NCEP_BEN_GO_GLDT_2019072400_010d_ATM
            String fullFileName = FileUtils.getNameNotSuffix(ncXmlFile.getName());
            //文件名后缀，如：.xml
            String fileExtend = FileUtils.getExtend(ncXmlFile.getName(), "");
            //如果后缀不是xml文件不解析
            if (!fileExtend.equals("xml")) {
                //删除不是xml的文件
                beifenFile(filePath, "fail", ncXmlFile);
                //记录错误日志
//                addAutoLog("文件" + ncXmlFile.getName() + "解析失败,不是xml文件", Globals.Log_Type_AUTO, Globals.Log_Leavel_ERROR);
                ncXmlFile.delete();
                return;
            }
            //查询是否存在相关产品
            OProduct p = new OProduct();
            p.setNameRule(fileName);
            List<OProduct> products = productService.selectOProductList(p);
            if (products != null && products.size() > 0) {
                OProduct product = products.get(0);
                //查找相关的压缩文件
                ONcFile f = new ONcFile();
                f.setFileName(fullFileName + "." + product.getFileType());
                List<ONcFile> ncFiles = oNcFileMapper.selectONcFileList(f);
                if (ncFiles != null && ncFiles.size() > 0) {
                    ONcFile ncFile = ncFiles.get(0);
                    //解析xml
                    SAXReader reader = new SAXReader();
                    org.dom4j.Document doc = reader.read(ncXmlFile);
                    //是否成功
                    String isSuccess = doc.getRootElement().elementText("IsSuccess");
                    String errorMessage = "1";
                    //失败时
                    if (!("TRUE").equals(isSuccess) && !("SUCCESS").equals(isSuccess)) {
                        errorMessage = doc.getRootElement().elementText("ErrorMessage");
                        //失败时做相关记录
                        //删除文件
                        beifenFile(filePath, "fail", ncXmlFile);
                        //记录错误日志
//                        addAutoLog("文件" + (fullFileName + "." + product.getFileType()) + "转换NC文件失败,失败原因:" + errorMessage, Globals.Log_Type_AUTO, Globals.Log_Leavel_ERROR);
                        ncXmlFile.delete();
                    } else {
                        //查找OutputFile节点
                        org.dom4j.Element outputFile = doc.getRootElement().element("OutputFile");
                        //输出的文件数
                        String outputFileNumber = outputFile.elementText("OutputFileNumber");
                        //文件输出的节点
                        org.dom4j.Element outputFileList = outputFile.element("OutputFileList");
                        //循环文件输出数
                        for (int i = 1; i <= Integer.parseInt(outputFileNumber); i++) {
                            //文件全路径
                            String unFile = outputFileList.elementText("OutputFileList" + i);
                            //文件所在文件夹
                            String unPath = unFile.substring(0, unFile.lastIndexOf("/"));
                            //文件名
                            String unFilename = unFile.substring(unFile.lastIndexOf("/") + 1);
                            //文件大小
                            long unSize = getFileSizes(new File(unFile));
                            BigDecimal unFileSize = new BigDecimal(unSize / 1024.0 / 1024.0).setScale(2, BigDecimal.ROUND_HALF_UP);

                            ONcUnzip ncUnzip = new ONcUnzip();
                            ncUnzip.setFileName(unFilename);
                            ncUnzip.setFtpPath(unPath);
                            ncUnzip.setFilePath(unPath);
                            ncUnzip.setFileSize(unFileSize);
                            ncUnzip.setProductId(product.getId());
                            ncUnzip.setOMetadataId(ncFile.getoMetadataId());
                            ncUnzip.setDel(0);
                            //nc文件时间
                            ncUnzip.setCreateDate(ncFile.getCreateDate());
                            ncUnzip.setUpdateDate(new Date());
                            ncUnzip.setDepartId(ncFile.getDepartId());
                            ncUnzip.setNcFileId(ncFile.getId());
                            //ncUnzip.setReleaseId(productReleaseEntity.getId());
                            ncUnzipService.insertONcUnzip(ncUnzip);


                            beifenFile(filePath + "/backups/" + productDateName, "", ncXmlFile);
                            ncXmlFile.delete();

                            String ncInputXmlPath = DictUtils.getDictLabel2("params", "ncInputXmlPath", "/cloud/xml/input");
                            String xmlFilePath = ncInputXmlPath + "/" + ncXmlFile.getName();
                            logger.info("删除的原xml地址：xmlFilePath==============：" + xmlFilePath);
                            File xmlFile = new File(xmlFilePath);
                            if (xmlFile.exists()) {
                                xmlFile.delete();
                            }
                        }
                    }
                } else {
                    //删除文件
                    beifenFile(filePath, "fail", ncXmlFile);
                    //记录错误日志
//                    addAutoLog("文件" + ncXmlFile.getName() + "解析失败,没有对应的nc文件", Globals.Log_Type_AUTO, Globals.Log_Leavel_ERROR);
                    ncXmlFile.delete();
                }
            } else {
                //删除文件
                beifenFile(filePath, "fail", ncXmlFile);
                //记录错误日志
//                addAutoLog("文件" + ncXmlFile.getName() + "解析失败,没有对应的产品", Globals.Log_Type_AUTO, Globals.Log_Leavel_ERROR);
                ncXmlFile.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //备份删除文件
            beifenFile(filePath, "fail", ncXmlFile);
            //记录错误日志
//            addAutoLog("文件" + ncXmlFile.getName() + "解析失败,失败原因:" + e.getMessage(), Globals.Log_Type_AUTO, Globals.Log_Leavel_ERROR);
            ncXmlFile.delete();
        }
    }

    /**
     * 发送电子邮件
     *
     * @param smtpHost 发信主机
     * @param receiver 邮件接收者
     * @param copy     抄送列表
     * @param title    邮件的标题
     * @param content  邮件的内容
     * @param sender   邮件发送者
     * @param user     发送者邮箱用户名
     * @param pwd      发送者邮箱密码
     * @throws Exception
     */
    public void sendSuEmail(String smtpHost, String receiver, String copy,
                            String title, String content, String sender, String user, String pwd)
            throws Exception {
        Properties props = new Properties();
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.put("mail.host", smtpHost);
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", smtpHost);//发信的主机，这里要把您的域名的SMTP指向正确的邮件服务器上，这里一般不要动！
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.port", "465");
        // 创建验证器
        Authenticator auth = new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                // 密码验证
                return new PasswordAuthentication("ybzx_cloud@163.com", "RGGPHAMXBCPVMWNZ");
            }
        };
        Session s = Session.getDefaultInstance(props, auth);
        s.setDebug(true);
        MimeMessage message = new MimeMessage(s);
        // 给消息对象设置发件人/收件人/主题/发信时间
        // 发件人的邮箱
        InternetAddress from = new InternetAddress(sender);
        message.setFrom(from);
        String[] receivers = receiver.split(",");
        InternetAddress[] to = new InternetAddress[receivers.length];
        for (int i = 0; i < receivers.length; i++) {
            to[i] = new InternetAddress(receivers[i]);
        }
        message.setRecipients(Message.RecipientType.TO, to);
        String[] copys = copy.split(",");
        InternetAddress[] cc = new InternetAddress[copys.length];
        for (int i = 0; i < copys.length; i++) {
            cc[i] = new InternetAddress(copys[i]);
        }
        message.setRecipients(Message.RecipientType.CC, cc);

        message.setSubject(title);
        message.setSentDate(new Date());
        // 给消息对象设置内容
        BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象
        mdp.setContent(content, "text/html;charset=gb2312");// 给BodyPart对象设置内容和格式/编码方式防止邮件出现乱码
        Multipart mm = new MimeMultipart();// 新建一个MimeMultipart对象用来存放BodyPart对
        // 象(事实上可以存放多个)
        mm.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
        message.setContent(mm);// 把mm作为消息对象的内容

        message.saveChanges();
        Transport transport = s.getTransport("smtp");
        transport.connect(smtpHost, user, pwd);// 设置发邮件的网关，发信的帐户和密码，这里修改为您自己用的
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }

    public OMetadataElement getMaxAndMinValue(OMetadataElement metadataElement, String value) {
        String realValue = value.replaceAll("\\[", "")
                .replaceAll("\\]", "");
        String[] valueList = realValue.split(",");
        if (valueList.length == 1) {
            Double minValue = Double.parseDouble(valueList[0]);
            Double maxValue = Double.parseDouble(valueList[0]);
            String rang = "[" + minValue + "," + maxValue + "]";
            metadataElement.setElementRange(rang);
            metadataElement.setMaxValue(maxValue);
            metadataElement.setMinValue(minValue);
            metadataElement.setSpan(maxValue);
            metadataElement.setRealValue(realValue);
        } else {
            Double minValue = Double.parseDouble(valueList[0]);
            Double twoValue = Double.parseDouble(valueList[1]);
            Double maxValue = Double.parseDouble(valueList[valueList.length - 1]);
            Double span = twoValue - minValue;
            String rang = "[" + minValue + "," + maxValue + "]";
            metadataElement.setElementRange(rang);
            metadataElement.setMaxValue(maxValue);
            metadataElement.setMinValue(minValue);
            metadataElement.setSpan(span);
            metadataElement.setRealValue(realValue);
        }
        return metadataElement;
    }

    /**
     * 查找中文要素名
     *
     * @param elementEn
     * @return
     */
    public String chineseName(String elementEn) {
        OElementDict elementDict = new OElementDict();
        elementDict.setElementEn(elementEn);
        List<OElementDict> elementDictEntitys = elementDictService.selectOElementDictList(elementDict);
        if (elementDictEntitys == null || elementDictEntitys.size() == 0) {
            return elementEn;
        }
        return elementDictEntitys.get(0).getElementZh();
    }

    /**
     * 解压文件
     */
    private String fileJar(Map<String, String> map) throws Exception {
        logger.info("===================解压开始===================");
        String outPath = MapUtils.getString(map, "outFile");
        if (StringUtil.isNotEmpty(outPath)) {
            File fileCopy = new File(outPath);
            //判断文件夹是否存在,如果不存在则创建文件夹
            if (!fileCopy.exists()) {
                fileCopy.mkdirs();
            }
        }

        logger.info("===================创建解压根目录完成===================");
        List<String> fileList = new ArrayList<>();
        if (".zip".equals(map.get("ext"))) {
            fileList = DecompressionUtils.unZip(map.get("inputFile").toString(), map.get("outFile"));
            logger.info("===================文件格式为.zip===================");

        }
        if (".tar".equals(map.get("ext"))) {
            fileList = DecompressionUtils.unTar(map.get("inputFile").toString(), map.get("outFile"));
            logger.info("===================文件格式为.tar===================");
        }
        if (".rar".equals(map.get("ext"))) {
            fileList = DecompressionUtils.unRar(map.get("inputFile").toString(), map.get("outFile"));
            logger.info("===================文件格式为.rar===================");
        }
        logger.info("===================解压完成。遍历存库开始===================");

        for (int i = 0; i < fileList.size(); i++) {
            ONcUnzip ncUnzip = new ONcUnzip();
            String unPath = fileList.get(i).substring(0, fileList.get(i).lastIndexOf("/"));
            String unFilename = fileList.get(i).substring(fileList.get(i).lastIndexOf("/") + 1);
            long unSize = getFileSizes(new File(fileList.get(i)));
            BigDecimal unFileSize = new BigDecimal(unSize / 1024.0 / 1024.0).setScale(2, BigDecimal.ROUND_HALF_UP);
            ncUnzip.setFileName(unFilename);
            ncUnzip.setFtpPath(unPath.replace("\\", "/"));
            ncUnzip.setFilePath(unPath.replace("\\", "/"));
            ncUnzip.setFileSize(unFileSize);
            ncUnzip.setProductId(MapUtils.getString(map, "productId"));
            ncUnzip.setOMetadataId(MapUtils.getString(map, "metadataId"));
            ncUnzip.setDel(0);
            //nc文件时间
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
            String createdDate = MapUtils.getString(map, "ncFileDate");
            ncUnzip.setCreateDate(formatter.parse(createdDate.substring(0, 8)));
            ncUnzip.setUpdateDate(new Date());
            ncUnzip.setDepartId(MapUtils.getString(map, "departId"));
            ncUnzip.setNcFileId(MapUtils.getString(map, "ncFileId"));
            ncUnzip.setReleaseId(MapUtils.getString(map, "releaseId"));
            ncUnzipService.insertONcUnzip(ncUnzip);
        }
        logger.info("===================解压完成。遍历存库结束===================");

        return "success";
    }

    /**
     * 生成xml文件
     *
     * @param ncFile      nc文件对象
     * @param previewData 要素集合
     * @param xmlFile     xml文件地址
     * @param outDirPath  输出文件夹
     * @param mathNum     随机数
     * @return 返回结果xml路径
     * @throws IOException
     * @throws JDOMException
     */
    public String BuildXMLDoc(ONcFile ncFile, PreviewData previewData, String xmlFile, String outDirPath, int mathNum) throws IOException, JDOMException {
        //nc文件集合
        List<String> inputFiles = new ArrayList<>();
        //输出文件夹
        List<String> outFiles = new ArrayList<>();
        //结果xml路径
        List<String> xmlResults = new ArrayList<>();
        String inputFile = ncFile.getFilePath() + "/" + ncFile.getFileName();
        String fileName = FileUtils.getNameNotSuffix(ncFile.getFileName());
        String outFile = outDirPath;
        String xmlResult = outDirPath + "/" + fileName + mathNum + "_result.xml";
        inputFiles.add(inputFile);
        outFiles.add(outFile);
        xmlResults.add(xmlResult);

        // 创建根节点 并设置它的属性 ;
        Element root = new Element("task");
        // 将根节点添加到文档中；
        Document Doc = new Document(root);
        // 创建节点 inputfilelist;
        Element elementsIn = new Element("inputfilelist").setAttribute("num", inputFiles.size() + "");
        for (int i = 0; i < inputFiles.size(); i++) {
            elementsIn.addContent(new Element("NCFile").setText(inputFiles.get(i)).setAttribute("index", i + 1 + ""));
        }
        root.addContent(elementsIn);

        // 创建节点 outputfilelist;
        Element elementsOut = new Element("outputfilelist").setAttribute("num", outFiles.size() + "");
        for (int i = 0; i < outFiles.size(); i++) {
            elementsOut.addContent(new Element("NCFile").setText(outFiles.get(i)).setAttribute("index", i + 1 + ""));
        }
        root.addContent(elementsOut);

        // 创建节点 ReportFile
        Element reportFile = new Element("reportFile").setAttribute("num", xmlResults.size() + "");
        for (int i = 0; i < xmlResults.size(); i++) {
            reportFile.addContent(new Element("report").setText(xmlResults.get(i)).setAttribute("index", i + 1 + ""));
        }
        root.addContent(reportFile);

        // 创建节点 params
        Element params = new Element("params");
        for (OWorkOrderItem workOrderItem : previewData.getWorkDto()) {
            String elementEn = workOrderItem.getElement();
            params.addContent(new Element("attbution").setAttribute("name", elementEn).setAttribute("enable", "yes")
                    .setAttribute("start", workOrderItem.getMinValue() + "")
                    .setAttribute("end", workOrderItem.getMaxValue() + "")
                    .setAttribute("flag", workOrderItem.getFlag() + ""));
        }
        root.addContent(params);
        // 创建节点 result;
        Element result = new Element("result");

        System.out.println(previewData.getYaosu());
        //新加
        if (previewData.getYaosu() == null || previewData.getYaosu() == "") {
            previewData.setYaosu("time");
        }

        result.addContent(new Element("attbution").setAttribute("name", previewData.getYaosu()));
        if (StringUtils.isNoneBlank(previewData.getYaosu2())) {
            result.addContent(new Element("attbution").setAttribute("name", previewData.getYaosu2()));
        }
        root.addContent(result);
        // 创建节点 outtype;
        Element outtype = new Element("outtype");
        outtype.addContent(new Element("attbution").setAttribute("value", previewData.getType()));
        root.addContent(outtype);
        // 输出 books.xml 文件；
        // 使xml文件 缩进效果
        Format format = Format.getPrettyFormat();
        XMLOutputter XMLOut = new XMLOutputter(format);
        XMLOut.output(Doc, new FileOutputStream(xmlFile));

        return xmlResult;
    }

    public static boolean isDateInRange(Date dateToCheck, Date startDate, Date endDate) {
        long dateToCheckTime = dateToCheck.getTime();
        long startDateTime = startDate.getTime();
        long endDateTime = endDate.getTime();

        return dateToCheckTime >= startDateTime && dateToCheckTime <= endDateTime;
    }

    public static String IsPname(String filename, String filetime){
        String file_name = "";
        String[] split = filename.split(filetime);
        /**
         * 格式只有年
         */
        if(filetime.length()==4){
            file_name = split[0]+"YYYY"+split[1];
        }
        /**
         * 格式只有年 月
         */
        if(filetime.length()==6){
            file_name = split[0]+"YYYYMM"+split[1];
        }
        /**
         * 格式只有年 月 日
         */
        if(filetime.length()==8){
            file_name = split[0]+"YYYYMMDD"+split[1];
        }
        /**
         * 格式只有年 月 日 时
         */
        if(filetime.length()==10){
            file_name = split[0]+"YYYYMMDDHH"+split[1];
        }
        /**
         * 格式只有年 月 日 时 分
         */
        if(filetime.length()==12){
            file_name = split[0]+"YYYYMMDDHHMM"+split[1];
        }
        /**
         * 格式只有年 月 日 时 分 秒
         */
        if(filetime.length()==14){
            file_name = split[0]+"YYYYMMDDHHMMSS"+split[1];
        }
        return file_name;
    }


 /*   public static void main(String[] args) {
        // 指定要解压的tar文件路径
        String tarFilePath = "E:\\NMF_BEN_OSMWA_NWPACDT_2024122212_168h_WAV.tar";
        String outputDir = "E:\\jy";

        try {
            extractTarFile(tarFilePath, outputDir);
            System.out.println("TAR 文件已成功解压到指定目录。");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/

    public static void extractTarFile(String tarFilePath, String outputDir) throws IOException {
        try (InputStream is = Files.newInputStream(new File(tarFilePath).toPath());
             TarArchiveInputStream tarInput = new TarArchiveInputStream(is)) {

            TarArchiveEntry entry;
            while ((entry = tarInput.getNextTarEntry()) != null) {
                System.out.println();
                // 忽略目录条目
                if (entry.isDirectory()) {
                    continue;
                }

                // 构造输出文件路径
                File outputFile = new File(outputDir, entry.getName());
                System.out.println(outputFile.getName());
                // 确保输出文件的父目录存在
                outputFile.getParentFile().mkdirs();

                // 将条目内容写入文件
                try (FileOutputStream fos = new FileOutputStream(outputFile)) {
                    byte[] buffer = new byte[4096];
                    int len;
                    while ((len = tarInput.read(buffer)) != -1) {
                        fos.write(buffer, 0, len);
                    }
                    System.out.println("=======");
                }
            }
        }
    }
    //时间格式转换
    public LocalDateTime timezh(String dateTimeString){
        if(dateTimeString.length()==14){
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            // 解析字符串为LocalDateTime
            LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
            return dateTime;
        }else if(dateTimeString.length()==12){
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
            // 解析字符串为LocalDateTime
            LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
            return dateTime;
        }else if(dateTimeString.length()==10){
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHH");
            // 解析字符串为LocalDateTime
            LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
            return dateTime;
        }else if(dateTimeString.length()==8){
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            // 解析字符串为LocalDateTime
            LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
            return dateTime;
        }else if(dateTimeString.length()==6){
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
            // 解析字符串为LocalDateTime
            LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
            return dateTime;
        }else if(dateTimeString.length()==4){
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy");
            // 解析字符串为LocalDateTime
            LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
            return dateTime;
        }else{

            return null;
        }
    }
    public static String getgdny(String h){
        // 获取当前的LocalDate对象
        LocalDate currentDate = LocalDate.now();

        // 获取年份
        int year = currentDate.getYear();

        // 获取月份（1-12），格式化为两位数字（不足补0）
        int month = currentDate.getMonthValue();

        // 获取日份（1-31），格式化为两位数字（不足补0）
        int day = currentDate.getDayOfMonth();

        // 使用String.format格式化，%02d表示：数字类型、占2位、不足补0
        return String.format("%d%02d%02d%s", year, month, day, h);
    }

 /*   public static void main(String[] args) {
        String getgdny = getgdny("00");
        System.out.println(getgdny);
    }*/
    public static String getgdny1(String h){
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();

        // 通过minusDays方法获取前一天日期
        LocalDate previousDate = currentDate.minusDays(1);

        // 提取前一天的年份
        int year = previousDate.getYear();

        // 提取前一天的月份
        int month = previousDate.getMonthValue();

        // 提取前一天的日份
        int day = previousDate.getDayOfMonth();

        // 打印出前一天的年月日
        System.out.println("前一天的年份: " + year);
        System.out.println("前一天的月份: " + month);
        System.out.println("前一天的日份: " + day);
        return year+""+month+""+day+""+h;
    }

}
